繁体   English   中英

将ListView选中标记设置为由Android ListActivity中的程序选中/未选中

[英]Set ListView checkmark as checked/unchecked by program in Android ListActivity

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

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中每个项目的复选标记,并手动设置为选中/未选中。

我的问题是 :我想通过程序而不是通过手动设置来设置某些项目,以便对其进行检查/取消选中,并且选中标记也随之更改。 能做到吗,怎么做?

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

我认为Google的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);
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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