将ListView复选标记设置为Android ListActivity中的程序选中/取消选中

时间:2012-05-24 22:37:33

标签: android android-listview

我已经为我的Android应用程序推荐过的示例。在ListActivity中,在 OnCreate 方法之前,项目数组已预定义为

String[] items = new String[]{"Text for Item1", "text for item2", ....};

OnCreate 方法中,我使用最简单的方法设置适配器并显示下面的列表视图:

setListAdapter( new ArrayAdapter<String>(this,
 android.R.layout.simple_list_item_checked, items));

我已经覆盖了这个方法:

@Override    
 protected void onListItemClick(ListView l, View v, int position, long id)    
{     
     CheckedTextView textview = (CheckedTextView)v;
     textview.setChecked(!textview.isChecked());
} 

以上所有代码都运行良好。可以显示ListView中每个litem的复选标记,并手动设置选中/取消选中。

我的问题是: 我想按程序设置一些项目,而不是通过手动点击,进行选中/取消选中,也可以更改复选标记。它可以完成,怎么做?

感谢您提前的帮助

1 个答案:

答案 0 :(得分:0)

我认为Google的Android工程师Romain Guy在this中说可以解决你的问题:

Actually you want to use CheckedTextView with choiceMode. That's what
CheckedTextView is for. However, you should not be calling setChecked
from bindView(), but let ListView handle it. The problem was that you
were doing ListView's job a second time. You don't need listeners
(click on onlistitem), calls to setChecked, etc.

以下是我的解决方案:

class MyActivity extends ListActivity { // or ListFragment

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // some initialize

        new UpdateCheckedTask().execute(); // call after setListAdapter
    }

    // some implementation

    class UpdateChecked extends AsyncTask<Void, Void, List<Integer>> {

        @Override
        protected List<Integer> doInBackground(Void... params) {
            ListAdapter listAdapter = getListAdapter();
            if (listAdapter == null) {
                return null;
            }

            List<Integer> positionList = new ArrayList<Integer>();
            for (int position = 0; position < listAdapter.getCount(); position++) {
                Item item = (Cursor) listAdapter.getItem(position); // or cursor, depends on your ListAdapter implementaiton
                boolean checked = item.isChecked() // your model
                positionList.add(position, checked);
            }
            return positionList;
        }

        @Override
        protected void onPostExecute(List<Integer> result) { // setItemChecked in UI thread
            if (result == null) {
                return;
            }

            ListView listView = getListView();
            for (Iterator<Integer> iterator = result.iterator(); iterator.hasNext();) {
                Integer position = iterator.next();
                listView.setItemChecked(position, true);
            }
        }
    }
}