列表Item点击,CheckBox状态切换,滑动CheckBox状态保持
main.xml
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip"
android:id="@+id/ListView"/>
listitem.xml
android:id="@+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip">
android:id="@+id/wishname"
android:layout_width="100px"
android:layout_height="wrap_content"
android:gravity="left"
android:text="TextView01"
android:textSize="20dip"/>
android:id="@+id/checkBox1"
android:layout_width="40px"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="140dp"
android:focusable="false">
Main.java
importjava.util.HashMap;
importjava.util.Map;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.BaseAdapter;
importandroid.widget.CheckBox;
importandroid.widget.CompoundButton;
importandroid.widget.ListView;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassMainextendsActivity {
privateListView list;
privateListAdapter listadapter;
privateString[] arr =newString[20];
privateMap status =newHashMap();
/** Called when the activity is first created. */
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(inti=0;i<20;i++){
arr[i] = i+""+i+""+i+""+i;
status.put(i,false);
}
// 绑定Layout里面的ListView
list = (ListView) findViewById(R.id.ListView);
listadapter =newListAdapter();
// 添加并且显示
list.setAdapter(listadapter);
// 添加点击事件
list.setOnItemClickListener(newOnItemClickListener() {
publicvoidonItemClick(AdapterView parent, View view,
intposition,longid) {
Toast.makeText(Main.this,"Item点击事件", Toast.LENGTH_SHORT).show();
}
});
}
privateclassListAdapterextendsBaseAdapter {
publicintgetCount() {
returnarr.length;
}
publicObject getItem(intposition) {
returnposition;
}
publiclonggetItemId(intposition) {
returnposition;
}
publicView getView(finalintposition, View view, ViewGroup parent) {
// 获取布局文件
if(view ==null) {
view = getLayoutInflater().inflate(R.layout.listitem,null);
}
// 获取控件
TextView name = (TextView) view.findViewById(R.id.wishname);
CheckBox ck = (CheckBox) view.findViewById(R.id.checkBox1);
ck.setChecked(status.get(position));
if(arr !=null) {
name.setText(arr[position]);
ck.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(View v) {
status.put(position, !status.get(position));
Toast.makeText(Main.this,"CheckBox点击事件", Toast.LENGTH_SHORT).show();
}
});
}
returnview;
}
}
}