2010-08-24 50 views
2

是否有可能以编程方式访问CheckedTextViews列表中的特定行以更改其文本框的状态?以编程方式访问CheckedTextView列表中的特定行 - Android

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

我想,当用户离开活动保存复选框的状态,所以我在我的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方法中,我记得从数据库中检查过的项目,但我不知道如何行进返回到listview元素的id。我可以做些什么:

listView.getElementById(id_from_database).setChecked

我知道我不能使用的getElementById,但我在这里要说明我的意思事先

感谢

凯文

回答

1

这是伊夫最终做..但它似乎是一个完整的黑客。 基本上,我必须设置一个double for循环..一个遍历我的列表元素,一个迭代通过游标,我已经retreived我的检查列表状态(一个元素的简单数组ID,当状态是最后保存)

我的外部迭代通过列表元素检查每个id对循环通过设置为检查的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(); 

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

感谢

凯文

1

您可以拨打

listView.setItemChecked(int position, boolean value) 
+0

的事情是我没有在现在的位置是德产品的,我只有它的ID,这让我想知道是否有一些可以访问ListView项方法(在这种情况是一个CheckedTextView)通过它的id。 – 2010-08-24 14:47:51

+0

可能位置是适配器中的位置。如果您循环使用适配器,并且找到选中的项目,则可以调用该方法。这只是一个循环。 – Pentium10 2010-08-24 20:30:06

+0

并非如此,如果我在适配器中有20个项目,并且我需要检查其中的10个项目,我仍然必须检查适配器中的每个项目,以反映每个需要检查的项目,这需要嵌套循环 – 2010-08-25 07:20:45