如何在ListView中添加CheckBox

 我来答
匿名用户
推荐于2016-01-03
展开全部
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;
}

}
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式