【问题标题】:How do I get all the selected list Items using Checkbox如何使用复选框获取所有选定的列表项
【发布时间】:2015-09-27 13:52:02
【问题描述】:

我对每个列表项都使用Checkbox,现在我想在单击按钮时获取所有选定列表项的名称。

我也发布了AdapterActivity 类的代码,因为稍后我必须将选定的列表项显示到ListView 的另一个活动中。

但现在我只想在按钮单击时查看所有选定的列表项

适配器:

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // convert view = design
        ....................

        holder.tvName.setText(actorList.get(position).getName());           

        holder.checkBox.setOnCheckedChangeListener(null);

        holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    // add into arraylist
                  selectedname.add(actorList.get(position).getName());
                }else{
                    // remove from arraylist
                    selectedname.remove(actorList.get(position).getName());
                }

            }
        });

        return v;

    }   

【问题讨论】:

    标签: java android checkbox


    【解决方案1】:

    下面的代码对我来说很好,所以你可以试试这个

    activity_main.xml

    <LinearLayout 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:orientation="vertical">
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/select_btn"
        android:text="Select"/>
    
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview"/>
    

    list_row.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="4dp"
    android:orientation="horizontal" >
    
    <CheckBox
        android:id="@+id/cbBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >
    </CheckBox>
    
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_gravity="center_vertical"
        android:ellipsize="marquee" />
    

    服务

    import java.io.Serializable;
    public class Service implements Serializable
    {
    
    private static final long serialVersionUID = 1L;
    
    private String name;
    private boolean selected;
    
    public Service() {
        // TODO Auto-generated constructor stub
    }
    
    public Service(String name) {
        super();
        this.name = name;
    }
    
    
    public String getName() {
        return name;
    }
    
    public boolean isSelected() {
        return selected;
    }
    
    public void setSelected(boolean selected) {
        this.selected = selected;
    }
    
    public void setName(String name) {
        this.name = name;
    
    }
    

    }

    服务适配器

    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.util.ArrayList;
    public class ServiceAdapter extends BaseAdapter {
    ArrayList<Service> actorList;
    LayoutInflater vi;
    Context context;
    
    public ServiceAdapter(Context context,ArrayList<Service> objects) {
        this.context= context;
        this.vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.actorList = objects;
    }
    
    
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // convert view = design
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = vi.inflate(R.layout.list_row, null);
    
            holder.tvName = (TextView) convertView.findViewById(R.id.textView1);
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cbBox);
    
            convertView.setTag(holder);
        } else
            holder = (ViewHolder) convertView.getTag();
    
        holder.tvName.setText(actorList.get(position).getName());
        holder.checkBox.setChecked(actorList.get(position).isSelected());
    
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSelected = ((CheckBox)v).isChecked();
                actorList.get(position).setSelected(isSelected);
            }
        });
    
        return convertView;
    
    }
    
    
    static class ViewHolder {
    
        public TextView tvName;
        public CheckBox checkBox;
    
    }
    
    
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return actorList.size();
    }
    
    
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return actorList.get(position);
    }
    
    
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    
    public ArrayList<Service> getSelectActorList(){
        ArrayList<Service> list = new ArrayList<>();
        for(int i=0;i<actorList.size();i++){
            if(actorList.get(i).isSelected())
                list.add(actorList.get(i));
        }
        return list;
    }
    

    }

    MainActivity

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        final ListView listView = (ListView)findViewById(R.id.listview);
        listView.setAdapter(new ServiceAdapter(this,sampleData()));
    
        Button btn = (Button)findViewById(R.id.select_btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<Service> actorList = ((ServiceAdapter)listView.getAdapter()).getSelectActorList();
                Toast.makeText(MainActivity.this,""+actorList.size(),Toast.LENGTH_LONG).show();
            }
        });
    
    }
    
    
    public ArrayList<Service> sampleData(){
        ArrayList<Service> dataList = new ArrayList<>();
        for(int i=0;i<30;i++){
            Service servic = new Service();
            servic.setName("Test"+i);
            dataList.add(servic);
        }
    
        return dataList;
    }
    

    }

    【讨论】:

      【解决方案2】:

      这可能会对你有所帮助。

      ArrayList<String> selectedname  = new ArrayList<String>();
      
      @Override
          public View getView(final int position, View convertView, ViewGroup parent) {
              // convert view = design
              View v = convertView;
              if (v == null) {
                  holder = new ViewHolder();
                  v = vi.inflate(Resource, null);
      
                  holder.tvName = (TextView) v.findViewById(R.id.textView1);          
                  holder.checkBox = (CheckBox) v.findViewById(R.id.cbBox);
      
                  v.setTag(holder);
              } else {
                  holder = (ViewHolder) v.getTag();
              }
      
              holder.tvName.setText(actorList.get(position).getName());  
             checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                  @Override
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                      if(isChecked){
                          // add into arraylist
                        selectedname.add(actorList.get(position).getName());
                      }else{
                          // remove from arraylist
                          selectedname.remove(actorList.get(position).getName());
                      }
      
                  }
              });
      
              return v;
      
          }
      
          static class ViewHolder {
      
              public TextView tvName; 
              public CheckBox checkBox;
      
          }
      

      将此选定的selectedname List 传递给另一个活动。在Button点击pass List between Activity like

      【讨论】:

      • 嘿兄弟,我正在使用你的方式,我刚刚更新了上面的代码检查,但我仍然不知道如何在按钮单击时显示所有检查的项目列表
      • 能否请检查行在按钮单击 ArrayList mselectedname = adapterObject.selectedname;
      • 你可以从ServiceAdapter中获取adapterObject = new ServiceAdapter(你需要的数据在这里传递);
      • 兄弟抱歉,但我仍然不知道如何使用单击按钮显示所有选定的项目(也进入另一个活动)
      • 看到在你的Button点击首先你需要得到Selected List项的名字,然后你需要将该列表传递给你需要的第二个Activity,根据选择的列表项的名字,你可以显示列表。
      【解决方案3】:

      最好的方法是:

      使用布尔值 isChecked 作为属性创建模型

      public Class CheckModel{
          String name;
          Boolean isChecked;
      
          public CheckModel(String name,Boolean isChecked){
              this.name = name;
              this.isChecked = isChecked;
          }
      
          //setter and getter here
      
      }
      

      将模型添加到arraylist时,默认设置isChecked为false

       arrayList.add(new CheckModel("title",false));
      

      现在在 Adapter 的 getView() 函数中将 isChecked 属性更改为 true onChecked

      arrayList.get(position).setChecked(true);

      最后,当您想要所有检查项目的名称时,请执行此操作

      for(int i = 0; i<arrayList.size;i++){
          if(arrayList.get(i).getisChecked()){
              //retreive the name
          }else{
              //ignore
          }
      }
      

      【讨论】:

        【解决方案4】:

        为此,请执行以下操作

        Im MyAdapter 创建类级变量

        public boolean[] checked;
        

        并编写 onCheckedChanged 事件

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
           boolean isChecked) {
        checked[position] = select.isChecked();
        }
        

        现在您可以访问布尔数组,如下所示

        ListAdapter adapter = listView.getAdapter(); 
        boolean[] check =((MyAdapter) adapter).checked;
        

        现在您可以提取选中的项目

        希望对你有用

        编辑:

        线下

        holder.checkBox = (CheckBox) v.findViewById(R.id.cbBox);
        

        像这样添加监听器

        holder.checkBox.setOnCheckedChangeListener(new    CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView,
              boolean isChecked) {
              checked[position] = select.isChecked();
          }
        });
        

        【讨论】:

          【解决方案5】:

          创建新的arraylist并将复选框项目插入其中

          ArrayList<String> checkedSelection = new ArrayList<String>();
          
          
              holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                          @Override
                          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                              if(isChecked){
                                  // add into arraylist
                                     checkedSelection.add(holder.checkBox.getText().toString());
                              }else{
                                  // remove from arraylist
                                   checkedSelection.remove(position);
                              }
                          }
                      });
          

          在按钮上单击将数组列表发送到另一个活动并加载列表视图

          【讨论】:

          • 在你的这条线下 holder.tvName.setText(actorList.get(position).getName());
          • 检查我更新的代码,让我知道我必须在哪里进行更改
          • 而不是 holder.checkBox.setOnClickListener(new OnClickListener() { 你必须使用 holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
          • 我已经更新了我的代码,如何在按钮点击时显示项目列表
          • 您可以在 MainActivity 中创建一个静态 Arraylist checkedSelection,然后在选中的复选框中添加或删除项目 MainActivity.checkedSelection.add() 或 MainActivity.checkedSelection.remove() 并发送到另一个Intent 中的活动为 toOtherActivity.putStringArrayListExtra("selected_list", checkedSelection);或将其存储在共享偏好中并将其放入另一个活动中
          【解决方案6】:

          为此,您必须在 Actor bean 类中维护 Checkbox

          我已经更新了你的适配器类的getView() 方法。看看吧。

          @Override
              public View getView(final int position, View convertView, ViewGroup parent) {
                  // convert view = design
                  View v = convertView;
                  ViewHolder holder;
                  if (v == null) {
                      holder = new ViewHolder();
                      v = vi.inflate(Resource, null);
                      holder.tvName = (TextView) v.findViewById(R.id.textView1);
                      holder.checkBox = (CheckBox) v.findViewById(R.id.cbBox);
                      v.setTag(holder);
                  } else {
                      holder = (ViewHolder) v.getTag();
                  }
                  holder.tvName.setText(actorList.get(position).getName());
                  holder.checkBox.setOnCheckedChangeListener(null);
                  holder.checkBox.setChecked(actorList.get(position).getStatus());
                  holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                      @Override
                      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                          actorList.get(position).setStatus(isChecked);
                      }
                  });
                  return v;
              }
          

          确保将getStatus()setStatus(boolean) 添加到您的bean 类中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-11-06
            • 1970-01-01
            • 1970-01-01
            • 2011-09-25
            • 2011-08-02
            • 1970-01-01
            • 2015-02-07
            • 1970-01-01
            相关资源
            最近更新 更多