代码之家  ›  专栏  ›  技术社区  ›  Kevin Bradshaw

通过编程访问CheckedTextView列表中的特定行-Android

  •  2
  • Kevin Bradshaw  · 技术社区  · 15 年前

    我的程序有一个listview,它有几个CheckedTextView,用户可以按它来切换状态。

    我想在用户离开活动时保存复选框的状态,因此在onPause方法中:

    public void onPause(){
             super.onPause();
             SparseBooleanArray positions;
             positions = listView.getCheckedItemPositions();
             ListAdapter items = listView.getAdapter();
             int j = items.getCount();
    
             ArrayList<Long> ids = new ArrayList<Long>();
             for (int k =0; k < j;k++){
                 if(positions.get(k)==true){
                     ids.add(items.getItemId(k));   
                 }
             } 
             this.application.getServicesHelper().open();
             this.application.getServicesHelper().storeServices(ids,visit_id);
             this.application.getServicesHelper().close();
         }
    

    它非常简单地迭代列表视图,将选中的项添加到ArrayList中,然后将ID列表保存到数据库中。

    到目前为止,在onStart方法中,我从数据库中调用了选中的项,但是我不知道如何将返回的id转移到listview元素。我可以这样做吗:

    listView.getElementById(id_from_database).setChecked ?

    提前谢谢

    凯文

    2 回复  |  直到 15 年前
        1
  •  1
  •   Pentium10    15 年前

    listView.setItemChecked(int position, boolean value)
    
        2
  •  1
  •   Kevin Bradshaw    15 年前

    这就是我最后要做的。。但这似乎是一个完整的黑客。 基本上我得设置一个双for循环。。一个遍历我的列表元素,一个遍历我检索了我的检查列表状态的游标(一个简单的元素id数组,在上次保存状态时被检查)

        // mAdapter is contains the list of elements I want to display in my list. 
    ServiceList.this.setListAdapter(mAdapter);
    
            // Getting a list of element Ids that had been previously checked by the user. getState is a function I have defined in my ServicesAdapter file.
    
        Cursor state = ServiceList.this.application.getServicesHelper().getState(visit_id);
        int checks = state.getCount();
        int check_service;               
        int c = mAdapter.getCount();
        if(checks>0){
            state.moveToFirst(); 
            for (int i=0; i<checks; i++) { 
                // set check_service = the next id to be checked
                check_service = state.getInt(0);
                for(int p=0;p<c;p++){
    
                    if(mAdapter.getItemId(p)==check_service){
                            // we have found an id that needs to be checked. 'p' corresponds to its position in my listView
                        listView.setItemChecked(p,true);
                        break;
                    }
                }
                state.moveToNext(); 
            } 
        }
        ServiceList.this.application.getServicesHelper().close();
    

    请告诉我有一个更有效的方法来实现这一点!!

    谢谢

    凯文

    推荐文章