Get Selected Item Using Checkbox in Listview

前端 未结 9 695
醉酒成梦
醉酒成梦 2020-11-22 09:36

I am creating an Android application where I have a ListView that displays all of the applications that were installed in my mobile phone.

My ListView is customized,

相关标签:
9条回答
  • 2020-11-22 09:56

    I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/source_container"
        >
        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:id="@+id/menu_source_icon"
            android:background="@drawable/bla"
            android:layout_margin="5dp"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/menu_source_name"
            android:text="Test"
            android:textScaleX="1.5"
            android:textSize="20dp"
            android:padding="8dp"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:textColor="@color/source_text_color"/>
        <CheckBox
            android:layout_width="40dp"
            android:layout_height="match_parent"
            android:id="@+id/menu_source_check_box"/>
    
    </LinearLayout>
    

    Solution: add attribute

    android:focusable="false"
    

    to CheckBox control.

    0 讨论(0)
  • 2020-11-22 09:58

    You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.

    More reference for this : listview with checkbox in android

    Source code for model

    public class Model {
    
        private boolean isSelected;
        private String animal;
    
        public String getAnimal() {
            return animal;
        }
    
        public void setAnimal(String animal) {
            this.animal = animal;
        }
    
        public boolean getSelected() {
            return isSelected;
        }
    
        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
    

    put this in your custom adapter

     holder.checkBox.setTag(R.integer.btnplusview, convertView);
            holder.checkBox.setTag( position);
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                    TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                    Integer pos = (Integer)  holder.checkBox.getTag();
                    Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
    
                    if(modelArrayList.get(pos).getSelected()){
                        modelArrayList.get(pos).setSelected(false);
                    }else {
                        modelArrayList.get(pos).setSelected(true);
                    }
    
                }
            });
    

    whole code for customAdapter is

    public class CustomAdapter  extends BaseAdapter {
    
        private Context context;
        public static ArrayList<Model> modelArrayList;
    
    
        public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
    
            this.context = context;
            this.modelArrayList = modelArrayList;
    
        }
    
        @Override
        public int getViewTypeCount() {
            return getCount();
        }
        @Override
        public int getItemViewType(int position) {
    
            return position;
        }
    
        @Override
        public int getCount() {
            return modelArrayList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return modelArrayList.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
    
            if (convertView == null) {
                holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.lv_item, null, true);
    
                holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
                holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
    
                convertView.setTag(holder);
            }else {
                // the getTag returns the viewHolder object set as a tag to the view
                holder = (ViewHolder)convertView.getTag();
            }
    
    
            holder.checkBox.setText("Checkbox "+position);
            holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
    
            holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
    
            holder.checkBox.setTag(R.integer.btnplusview, convertView);
            holder.checkBox.setTag( position);
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                    TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                    Integer pos = (Integer)  holder.checkBox.getTag();
                    Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
    
                    if(modelArrayList.get(pos).getSelected()){
                        modelArrayList.get(pos).setSelected(false);
                    }else {
                        modelArrayList.get(pos).setSelected(true);
                    }
    
                }
            });
    
            return convertView;
        }
    
        private class ViewHolder {
    
            protected CheckBox checkBox;
            private TextView tvAnimal;
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 10:15

    Assuming you want to get items of row whose check boxes are checked at the click of a button. Assumption based on your title "Get Selected Item Using Checkbox in Listview when I click a Button".

    Try the below. Make only changes as below. Keep the rest the same.

    Explanation and discussion on the topic @

    https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

    MainActivity.java

    public class MainActivity extends Activity {
         AppInfoAdapter adapter ;
         AppInfo app_info[] ;
            @Override
            protected void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
    
    
                final ListView listApplication = (ListView)findViewById(R.id.listApplication);
                Button b= (Button) findViewById(R.id.button1);
                b.setOnClickListener(new OnClickListener()
                {
    
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
    
                        StringBuilder result = new StringBuilder();
                        for(int i=0;i<adapter.mCheckStates.size();i++)
                        {
                            if(adapter.mCheckStates.get(i)==true)
                            {
    
                                               result.append(app_info[i].applicationName);
                                result.append("\n");
                            }
    
                        }
                        Toast.makeText(MainActivity.this, result, 1000).show();
                    }
    
                });
    
                ApplicationInfo applicationInfo = getApplicationInfo();
                PackageManager pm = getPackageManager();
                List<PackageInfo> pInfo = new ArrayList<PackageInfo>();
                pInfo.addAll(pm.getInstalledPackages(0));
                app_info = new AppInfo[pInfo.size()];
    
                int counter = 0;
                for(PackageInfo item: pInfo){
                    try{
    
                        applicationInfo = pm.getApplicationInfo(item.packageName, 1);
    
                        app_info[counter] = new AppInfo(pm.getApplicationIcon(applicationInfo), 
                                String.valueOf(pm.getApplicationLabel(applicationInfo)));
    
                        System.out.println(counter);
    
                    }
                    catch(Exception e){
                         System.out.println(e.getMessage());
                    }
    
                    counter++;
                }
    
               adapter = new AppInfoAdapter(this, R.layout.listview_item_row, app_info);
                listApplication.setAdapter(adapter);
    
            }
    }
    

    activity_main.xml ListView with button at the buton

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" >
    
        <ListView
            android:layout_width="fill_parent"
            android:id="@+id/listApplication"
            android:layout_height="fill_parent"
            android:layout_above="@+id/button1"
            android:text="@string/hello_world" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="Button" />
    
    </RelativeLayout>
    

    AppInfoAdapter

    public class AppInfoAdapter extends ArrayAdapter<AppInfo> implements CompoundButton.OnCheckedChangeListener
    {  SparseBooleanArray mCheckStates; 
    
        Context context;
        int layoutResourceId;
        AppInfo  data[] = null;
    
        public AppInfoAdapter(Context context, int layoutResourceId, AppInfo[] data){
            super(context, layoutResourceId,data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
            mCheckStates = new SparseBooleanArray(data.length);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
    
            View row = convertView;
            AppInfoHolder holder= null;
    
            if (row == null){
    
                LayoutInflater inflater = ((Activity)context).getLayoutInflater();
                row = inflater.inflate(layoutResourceId, parent, false);
    
                holder = new AppInfoHolder();
    
                holder.imgIcon = (ImageView) row.findViewById(R.id.imageView1);
                holder.txtTitle = (TextView) row.findViewById(R.id.textView1);
                holder.chkSelect = (CheckBox) row.findViewById(R.id.checkBox1);
    
                row.setTag(holder);
    
            }
            else{
                holder = (AppInfoHolder)row.getTag();
            }
    
    
            AppInfo appinfo = data[position];
            holder.txtTitle.setText(appinfo.applicationName);
            holder.imgIcon.setImageDrawable(appinfo.icon);
           // holder.chkSelect.setChecked(true);
            holder.chkSelect.setTag(position);
            holder.chkSelect.setChecked(mCheckStates.get(position, false));
            holder.chkSelect.setOnCheckedChangeListener(this);
            return row;
    
        }
        public boolean isChecked(int position) {
            return mCheckStates.get(position, false);
        }
    
        public void setChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
    
        }
    
        public void toggle(int position) {
            setChecked(position, !isChecked(position));
    
        }
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
    
         mCheckStates.put((Integer) buttonView.getTag(), isChecked);    
    
    }
    static class AppInfoHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
        CheckBox chkSelect;
    
    }
    }
    

    Here's the snap shot

    enter image description here

    0 讨论(0)
提交回复
热议问题