Johan
Johan

Reputation: 79

Checkbox in listview

I would like to set a checkbox in a listview's click-event. How can I set the right checkbox?

This is my code:

    listView.setOnItemLongClickListener(new OnItemLongClickListener()
    {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapter, View view,
                int position, long id)
        {
                         Checkbox checkbox = ??
                         checkbox.setChecked(true);

            return true;
        }
    });

Upvotes: 0

Views: 930

Answers (3)

Wangchao0721
Wangchao0721

Reputation: 909

First,JavaCode in Activity:

listview.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView parentView, View childView, int position, long id)    
    {
         CheckBox cb = (CheckBox) childView.findViewById(R.id.file_checkbox);
         cb.setChecked(true);
    }
}

Second,Do not forget one thing about CheckBox in layout xml, Set android:focusable="false" to checkbox in xml , otherwise listview can`t get click event.

Third,And Most important thing,Because when listview scroll , getView() in adapter will be called unexcepted , the checkbox will be mobified unexcepted , so set checkbox status in getView() is very important , Here is my example in getView():

if(mFiles[position].isSeleted){
    checkbox.setChecked(true);
} else {
    checkbox.setChecked(false);
}

Upvotes: 1

Richa
Richa

Reputation: 3193

Try out http://www.vogella.de/articles/AndroidListView/article.html may help u

Upvotes: 1

Nikunj Patel
Nikunj Patel

Reputation: 22066

you need a custom Adapter base list-view you can get from :: Here

Upvotes: 0

Related Questions