如何使用Checkbox获取所有选定的列表项

时间:2015-07-09 09:20:21

标签: java android checkbox

我对每个列表项使用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;

    }   

6 个答案:

答案 0 :(得分:5)

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

<强> 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;

}

}

<强> ServiceAdapter

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

}

答案 1 :(得分:3)

这可能对你有所帮助。

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

答案 2 :(得分:0)

创建新的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);
                    }
                }
            });

并点击按钮,将arraylist发送到另一个活动并加载listview

答案 3 :(得分:0)

这样做如下

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

答案 4 :(得分:0)

为此,您必须在Checkbox bean类

中维护Actor

我已更新适配器类的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类。

答案 5 :(得分:0)

最好的方法是:

使用布尔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
    }
}