[Android] MultiChoiceListener functionality in your ListViews, in 6 easy steps (Advanced)

This tutorial assumes that you know how to handle ListViews, ListAdapters, and Fragments. If someone needs deeper explaination, ask it on a comment.

Step 1.- MyFragment.java

public class MyFragment extends Fragment implements MultiChoiceModeListener
{
...

Step 2.- my_fragment.xml

<ListView 
 android:id="@+id/my_list"
 android:layout_height="match_parent"
 android:layout_width="wrap_content"
 android:choiceMode="multipleChoiceModal"
 android:entries="@array/values"
 />

Step 3.- MyFragment.java – onViewCreated()

mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int position,
long arg3) {
mListView.setItemChecked(position, !mListView.isItemChecked(position));
}
});
mListView.setMultiChoiceModeListener(this);

Step 4.- MyFragment.java

@Override
 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
 return false;
 }
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,long id, boolean checked) {
}

Step 5.- my_fragment_row.xml

<com.company.myapp.view.CheckableRelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 > 

Step 6.- CheckableRelativeLayout.java

public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
 private boolean mChecked;

 public CheckableRelativeLayout(Context context) {
 super(context);
 }
 
 public CheckableRelativeLayout(Context context, AttributeSet attrs) {
 super(context, attrs);
 }

 public CheckableRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
 super(context, attrs, defStyle);
 }
  
 public void setChecked(boolean checked) {
 mChecked = checked;
 refreshDrawableState();
 
 int bgResource = checked ? R.drawable.selection_mask_blue : android.R.color.transparent;
 setBackgroundResource(bgResource);
 }

 public boolean isChecked() {
 return mChecked;
 }

 public void toggle() {
 setChecked(!mChecked);
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s