如何在ListView中添加CheckBox
1个回答
2015-08-03 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517195
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
package com.billy.demo;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
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.CompoundButton.OnCheckedChangeListener;
public class TestListViewAndCheckbox extends ListActivity {
/** Called when the activity is first created. */
Context context = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = getApplicationContext();
setListAdapter(new MyListAdapter());
}
class MyListAdapter extends BaseAdapter{
String data[] = new String[]{"apple", "pear", "banana", "orange","apple", "pear", "banana", "orange","apple", "pear", "banana", "orange"};
List<Integer> checkPosition = new ArrayList<Integer>(data.length);
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (null == convertView){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
TextView text = (TextView)convertView.findViewById(R.id.info);
final CheckBox checkbox = (CheckBox)convertView.findViewById(R.id.checkstatus);
checkbox.setTag(new Integer(position));
text.setText(data[position]);
if (checkPosition != null){
checkbox.setChecked((checkPosition.contains(new Integer(position)) ? true : false));
}else{
checkbox.setChecked(false);
}
checkbox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked){
if (!checkPosition.contains(checkbox.getTag())){
checkPosition.add((Integer)checkbox.getTag());
}
}else{
if (checkPosition.contains(checkbox.getTag())){
checkPosition.remove(checkbox.getTag());
}
}
}
});
return convertView;
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询