简体   繁体   中英

ListView of CheckBox in Android is visualized by strings instead of Checkboxes

I would like to create ListView of checkboxes, pass the List to it and when the object is added to list ListView will update itself. I defined ListView :

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

I added collection of Checkboxes to the listView :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_product_list,
            container, false);

    ListView listView = (ListView) rootView.findViewById(R.id.productList);
    ArrayList<CheckBox> list = new ArrayList<CheckBox>();
    CheckBox el = new CheckBox(rootView.getContext());
    el.setText("STH");
    list.add(el);
    ArrayAdapter<CheckBox> adapter = new ArrayAdapter<CheckBox>(rootView.getContext(),android.R.layout.simple_list_item_1, list);
    listView.setAdapter(adapter);       
    return rootView;
}

And the result is horrible:

在此处输入图片说明

I probably get Checkbox.toString() inside that ListView instead of list of checkboxes.

How to get list of checkboxes which I can tap and select and will be in one container.

The main problem comes from the fact that you are using 'android.R.layout.simple_list_item_1' for your adapter. This is a built in layout and only contains a single textview.

The best approach is to create you own view that consists of checkbox and textview.

Then create your own adapter to inflate the view and set the contents

public class CheckBoxListAdapter extends BaseAdapter{

 CheckBox[] boxes;

 public CheckBoxListAdapter(CheckBox[] boxes){
  this.boxes = boxes;
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent{
   View v = inflate.inflate(R.layout.single_list_item, parent, false);

   CheckBox cb = (CheckBox)v.findViewById(R.id.single_item_cb);
   cb.setChecked(boxes[position].getChecked());

   TextView cb = (TextView )v.findViewById(R.id.single_item_tv);
   cb.setText(boxes[position].getText());

   // Here you can attach listeners and customise components
   return v;
 }
}

For the XML view you just need a view with a textview and a checkbox matching those id's

Then just use this as your adapted instead.

Also with this method, as you have a Add button, you can write an add function to the adapter then it can handle your data and display for you :)

Hope this helps

EDIT: Found this, might be useful he explains pretty well http://www.vogella.com/tutorials/AndroidListView/article.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM