由于listview的一些特性,刚开始写这种需求的功能的时候都会碰到一些问题,重点就是存储每个checkbox的状态值,在这里分享出了完美解决方法:
布局文件:
[html]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
<LinearLayout
android:id="@+id/line"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/tv"
android:orientation="horizontal" >
<Button
android:id="@+id/bt_selectall"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:text="全选" />
<Button
android:id="@+id/bt_cancleselectall"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:text="反选" />
<Button
android:id="@+id/bt_deselectall"
android:layout_width="80dp"
android:layout_height="fill_parent"
android:text="取消选择" />
</LinearLayout>
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/line" />
</RelativeLayout>
listView 的item布局文件:
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/item_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1" />
<CheckBox
android:id="@+id/item_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center_vertical" />
</LinearLayout>
Activity:
[java]
public class Ex_checkboxActivity extends Activity {
private ListView lv;
private MyAdapter mAdapter;
private ArrayList<String> list;
private Button bt_selectall;
private Button bt_cancel;
private Button bt_deselectall;
private int checkNum; // 记录选中的条目数量
private TextView tv_show;// 用于显示选中的条目数量
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* 实例化各个控件 */
lv = (ListView) findViewById(R.id.lv);
bt_selectall = (Button) findViewById(R.id.bt_selectall);
bt_cancel = (Button) findViewById(R.id.bt_cancelselectall);
bt_deselectall = (Button) findViewById(R.id.bt_deselectall);
tv_show = (TextView) findViewById(R.id.tv);
list = new ArrayList<String>();
// 为Adapter准备数据
initDate();
// 实例化自定义的MyAdapter
mAdapter = new MyAdapter(list, this);
// 绑定Adapter
lv.setAdapter(mAdapter);
// 全选按钮的回调接口
bt_selectall.setOnClickListener(new OnClickListener() {
补充:移动开发 , Android ,