我通过将基本适配器类扩展到“cust_listadapter”(自定义适配器)来使用带有列表视图的复选框。在这种情况下,当我使用布尔数组来保存复选框的选择时,代码运行良好,但是当我将对象(bean)与数组列表一起使用时,代码运行不正确。每当我选择一个复选框时,所有复选框看到选择。下面,我展示了我的代码。
public class MainActivity extends Activity {
ListView l1;
cust_listadapter custom_adapter;
List<Integer> l_items;
List<State_Refresh> check_state;
State_Refresh ob_state;
Boolean b_check[]=new Boolean[50];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l_items=new ArrayList<Integer>();
ob_state=new State_Refresh();
check_state=new ArrayList<State_Refresh>();
for(int i=1;i<=50;i++)
{
l_items.add(i);
b_check[i-1]=false;
ob_state.setState(false);
ob_state.setButtonValue("OFF");
check_state.add(ob_state);
}
l1=(ListView) findViewById(R.id.list1);
custom_adapter=new cust_listadapter();
l1.setAdapter(custom_adapter);
l1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "huluhulu "+arg2, 0).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class cust_listadapter extends BaseAdapter
{
@Override
public int getCount() {
// TODO Auto-generated method stub
return l_items.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View_Holder viewHolder;
if(convertView==null)
{
convertView=getLayoutInflater().inflate(R.layout.list_items,null);
viewHolder=new View_Holder();
viewHolder.ch1=(CheckBox) convertView.findViewById(R.id.check_box1);
viewHolder.tv1=(TextView)
convertView.findViewById(R.id.textview1);
viewHolder.ch1.setFocusable(false);
viewHolder.ch1.setFocusableInTouchMode(false);
convertView.setTag(viewHolder);
viewHolder.ch1.setTag(check_state.get(position).getState());
}
else
{
viewHolder=(View_Holder) convertView.getTag();
viewHolder.ch1.setChecked(check_state.get(position).getState());
//getting value from boolean array
// viewHolder.ch1.setChecked(b_check[position]);
}
viewHolder.ch1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(viewHolder.ch1.isChecked())
{
check_state.get(position).setState(true);
b_check[position]=true;
}
else
{
b_check[position]=false;
check_state.get(position).setState(false);
}
}
});
return convertView;
}
}
class View_Holder
{
CheckBox ch1;
TextView tv1;
}
class State_Refresh
{
Boolean check_value;
public void setState(Boolean check_value)
{
this.check_value=check_value;
}
public Boolean getState()
{
return check_value;
}
}
}