开发者

How to get proper view in ListActivity to set OnCheckedChangeListener for CheckBox widget in Android

开发者 https://www.devze.com 2023-02-01 04:58 出处:网络
I have a ListActivity which will display three widgets for each row.One of them is a checkbox. public class GroceryItems extends ListActivity {

I have a ListActivity which will display three widgets for each row. One of them is a checkbox.

public class GroceryItems extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.grocery_items_list);
 setUpData();
}

In my setUpData() I'm using a SimpleAdapter (this is all a test case).

private void setUpData(){
// generate the maps
String[] from = new String[] {"checked", "item_name","quantity"};
int[] toDisplay = new int[] {R.id.checkbox1, R.id.text1, R.id.text2};

List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();

for(int i = 0; i < 20; i++){
HashMap<String, Object> map = new HashMap<String, Object>();
if(i==3){
map.put("checked", false);
}
else{
map.put("checked", true);
}
  map.put("item_name", items[i]);
  map.put("quantity","3");

  fillMaps.add(map);
}
ListView lv= getListView();


    SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.common_rowitem, from, toDisplay);
    lv.setAdapter(adapter);

    CheckBox cb = (CheckBox) lv.findViewById(R.id.checkbox1);
    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton cb, boolean isChecked) {            
            if(cb.isChecked()) {                    
                // action
            }
            else {
                // action
            }
        }           
    });


 }

On findViewById I always get a null returned and can't add the listener. I have also tried to use a view binder

   adapter.setViewBinder(new SimpleAdapter.ViewBinder() {

   public boolean setViewValue(View view, Object data,
 String textRepresentation) {
if (view.getId()==R.id.checkbox1){
  CheckBox cb = (C开发者_如何转开发heckBox) view;
  if (data != null){
   cb.setChecked((Boolean)data);
   return true;
  }
}
 return false;
 }
    });

This also fails to install the handler.

Here are the two layout views

grocery_items_list.xml

<?xml version="1.0" encoding="utf-8"?>

<ListView android:id="@+id/android:list"
      android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

common_rowitem.xml

<?xml version="1.0" encoding="utf-8"?>

Any suggestions or help is appreciated.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号