2010-08-24 36 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

相關問題