2011-09-13 39 views
0

編輯:基於問題的演變,我編輯了這個問題。getCheckedItemPositions()總是返回null(Android ListView)

首先,我知道有一些類似的問題,但他們每個人都有特定的差異,這使得答案沒用我...

我真的很感激,如果有人能幫助我,我真的很絕望這個問題...

所以問題是:我想填充一個ListView與複選框,並且不能使用simple_multiple_choice_mode(類似的東西),因爲我需要手動構建我的XML佈局 - 所以我使用的是list_item.xml文件:

<?xml version="1.0" encoding="utf-8"?> 
     <CheckBox 
xmlns:android="http://schemas.android.com/apk/res/android" android:paddingLeft="8mm" 
android:layout_width="fill_parent" 
     android:layout_height="wrap_content" android:id="@+id/nomeAPP" style="?listItem"> 
     </CheckBox> 

問題是,如果我使用simple_multiple(..)模式選項,getCheckedItemPositions正常工作。如果不這樣做(就像我在下面的代碼中)getCheckedItemPositions爲空。所以從我讀到的,這是一個常見的錯誤,需要一個處理程序作爲解決方法。但我不能讓處理程序工作,我在logcat中得到java.lang.NullPointerException異常。

任何人都可以幫我嗎?

我這個小漂亮的代碼:

this.setListAdapter(new ArrayAdapter<String>(this, 
        R.layout.list_item, aux)); 

      list.setItemsCanFocus(false); 
      list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
      list.setSelected(true); 
      list.setClickable(true); 
      list.setOnItemSelectedListener(new OnItemSelectedListener() { 
       public void onItemSelected(AdapterView<?> arg0, View arg1, 
         int arg2, long arg3) { 
        // Auto-generated method stub 

        Log.d("checked",""+arg2);   


       } 

       public void onNothingSelected(AdapterView<?> arg0) { 
        // Auto-generated method stub 
       } 

      }); 


      CheckBox c = (CheckBox) findViewById(R.id.nomeAPP); 
      c.setOnCheckedChangeListener(new OnCheckedChangeListener() { 
       public void onCheckedChanged(CompoundButton arg0, boolean arg1) { 
        CheckBox checkbox = (CheckBox)arg0; 
        boolean isChecked = checkbox.isChecked(); 

        if(isChecked == true) 
         Log.v("TAG", "true"); 
        else 
         Log.v("TAG", "false"); 
       } 
      }); 
+0

這個問題被編輯了很多次,標記並創建了新的問題。 – Tiago

回答

0

看起來這是使用setAdapter的一個錯誤,它使用setListAdapter解決。

讓我們來看看,文檔指出ListActivity應該使用

list=getListView(); 
<ListView android:id="@android:id/list" 

所以忘掉=「+ @ ID(....

現在我們可以在我們的活動知道 「去哪裏」 是List和現在我們可以使用

setListAdapter(new ArrayAdapter<String>(this, 
         R.Layout.List_item, aux)); 

,一切工作正常。

0

你必須設置你的ListView中choiceMode屬性,以獲得一個對象從這個方法背:

http://developer.android.com/reference/android/widget/AbsListView.html#getCheckedItemPositions%28%29

+0

我用另一個答案的建議,並且不起作用。 – Tiago

+0

因爲它看起來像你使用自己的複選框。一旦將choiceMode設置爲多,getCheckedItemPositions將使用ListView提供的複選框。如果你想在你的列表項目佈局中提供你自己的CheckBox,你需要在它上面使用一個OnCheckedChangedListener,並且使用它提供的信息來跟蹤被檢查的內容。 – Rich

+0

這就是我正在做的事情。你能檢查我更新的答案嗎? – Tiago

3

試試這個代碼

list = (ListView) findViewById(R.id.listagem); 
list.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item,R.id.nomeAPP,aux)); 
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 

//獲取檢查項目lik這個;

int count=list.getChildCount(); 
for(int i=1;i<=count;i++){ 
    if(list.isItemChecked(i)){ 
     //do your task/work 
    } 
} 
+0

不幸的是,仍然是同樣的問題。 – Tiago

+0

耶也不適合我 – A23149577