1

我曾为我的 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 中每个项目的复选标记可以显示并手动设置选中/取消选中。

我的问题是:我想通过程序设置一些项目,而不是通过手动单击来选中/取消选中,并且选中标记也随之更改。可以做到吗?怎么做?

我在这里先向您的帮助表示感谢

4

1 回答 1

0

我认为谷歌的 Android 工程师 Romain Guy 说的可以解决你的问题:

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);
            }
        }
    }
}
于 2012-05-30T14:57:08.407 回答