简体   繁体   中英

Listview custom adapter multiple choice selecting

I am trying to make a multiple_choice ListView.
I am using a custom adapter and custom layout.
but I couldn't make it happen.

The Activity (Fragment):

public class RegisterGroupFragment extends Fragment {
@Override
public void onViewCreated(View view, Bundle savedInstanceState){
    super.onViewCreated(view, savedInstanceState);
    GroupRepository.getInstance(getActivity().getApplication()).getGroups().observe(getActivity(), new Observer<ArrayList<Group>>() {
        @Override
        public void onChanged(ArrayList<Group> groups) {
            populateList(groups,view);
        }
    });
}
private void populateList(ArrayList<Group> groups,View view){
    ArrayList<NormalListModel> models = new ArrayList<>();
    for(int i=0;i<groups.size();i++){
        Group gp = groups.get(i);
        models.add(gp);
    }
    NormalListAdapter listAdapter = new NormalListAdapter(this.getActivity(),R.layout.fragment_normal_checked_task_list_row, models);
    ListView listView = (ListView) view.findViewById(R.id.groups_listview);
    listView.setAdapter(listAdapter);

    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    //listView.setItemChecked(2,true);
    listView.setMultiChoiceModeListener(new ListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            mode.setTitle(""+listView.getCheckedItemCount()+" گروه انتخاب شده");
            Log.d("multiple","multiple changed"+listView.getCheckedItemCount());
        }
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater menuInflater = mode.getMenuInflater();
            menuInflater.inflate(R.menu.menu_contextual_action_bar,menu);
            return true;
        }
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()){
                case R.id.menu_confirm:
                //action on clicking contextual action bar menu item

                    SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
                    for(int i =0;i<checkedItems.size();i++){

                        if(checkedItems.valueAt(i) == true){
                        }
                    }
                    mode.finish();
            }
            return true;
        }
        @Override
        public void onDestroyActionMode(ActionMode mode) {
        }
    });

    //for page #2
    /*listAdapter.setOnItemClickListener(new NormalListAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int id) {
            //((RegisterActivity) RegisterGroupFragment.this.getActivity()).usrGroupSet(id);
            ArrayList<Integer> arr = new ArrayList<>();
            arr.add(id);
            registerViewModel.setGroupId(arr);
        }
    });*/
}
}

and this is The NormalListAdapter:

public class NormalListAdapter extends ArrayAdapter {
//to reference the Activity
private final Activity context;

private ArrayList<NormalListModel> models;

private OnItemClickListener onItemClickListener;

public interface OnItemClickListener {
    void onItemClick(View view, int id);
}

public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
}

public NormalListAdapter(Activity context, ArrayList<NormalListModel> models){

    super(context, R.layout.fragment_normal_task_list_row, models);

    this.context=context;
    this.models = models;
}

public NormalListAdapter(Activity context,int layout, ArrayList<NormalListModel> models){

    super(context, layout, models);
    this.context=context;
    this.models = models;
}

public View getView(final int position, View view, ViewGroup parent) {
    LayoutInflater inflater=context.getLayoutInflater();
    View rowView=inflater.inflate(R.layout.fragment_normal_task_list_row, null,true);

    //this code gets references to objects in the listview_row.xml file
    TextView nameTextField = (TextView) rowView.findViewById(R.id.list_item_text_title);
    TextView infoTextField = (TextView) rowView.findViewById(R.id.list_item_text_info);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.list_item_image);

    //this code sets the values of the objects to values from the arrays
    final NormalListModel model = models.get(position);

    nameTextField.setText(model.getTitle());
    infoTextField.setText(model.getInfo());
    if(model.is_local_img()){
        imageView.setImageResource(model.getImage());
    }else{
        Glide.with(parent)
                .load(model.getImageUrl())
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .error(Glide.with(parent).load(R.drawable.fallback512).fitCenter().dontAnimate())
                .into(imageView);
    }

    //to every row listener, we will call a function
    // function has been initialized when adapter has been made
    if (onItemClickListener != null) {
        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                    onItemClickListener.onItemClick(v, model.getId());
            }
        });
    }
    return rowView;
}
}

this is the custom layout:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutDirection="rtl"
    >
    <ImageView
        android:layout_width="@dimen/finger"
        android:layout_height="@dimen/finger"
        android:id="@+id/list_item_image"
        android:src="@drawable/ic_auth_confirm"
        android:layout_marginEnd="@dimen/text_title"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/list_item_text_title"
            android:textSize="18sp"
            android:gravity="center_vertical"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/list_item_text_info"
            android:textSize="12sp"
            />
    </LinearLayout>
    <CheckedTextView
        android:id="@+id/text3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:checkMark="?android:attr/listChoiceIndicatorSingle" />

    </LinearLayout>

this is menu to show in action bar:

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <item
        android:id="@+id/menu_confirm"
        android:orderInCategory="100"
        android:showAsAction="ifRoom|withText"
        android:title="Delete"
        android:icon="@android:drawable/ic_menu_send"
        tools:ignore="AppCompatResource" />
</menu>

The ListView is properly shown but multiple_choice ain't working. I don't know what I'm missing??!

Create a list of

List<NormalListModel> selectedModel 

in your getView() method. Everytime user clicks on an item of list view, keep adding that item to this list by the below method and also make sure to check if the user selects the selected item again, remove it from the selectedModel list.

rowView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View v) {
         if (selectedModel != null && selectedModel.contains(model) {
             selectedModel.remove(model);
         }
         else {
             selectedModel.add(model);
         }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM