简体   繁体   English

Listview自定义适配器多项选择选择

[英]Listview custom adapter multiple choice selecting

I am trying to make a multiple_choice ListView.我正在尝试制作一个 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:这是 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. ListView 已正确显示,但 multiple_choice 不起作用。 I don't know what I'm missing??!我不知道我错过了什么??!

Create a list of创建一个列表

List<NormalListModel> selectedModel 

in your getView() method.在您的getView()方法中。 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.每次用户点击列表视图的一个项目时,通过下面的方法将该项目添加到此列表中,并确保检查用户是否再次选择了所选项目,将其从 selectedModel 列表中删除。

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);
         }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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