2012-04-04 71 views
1

我想用LinearLayout項目(它將包含CheckedTextView和多個textview)實現listview。
所以我想在ListView中使用LinearLayout而不是CheckedTextView。 我試過了,但單選按鈕狀態沒有改變。
我的代碼:如何在Android Listview中使用LinearLayout代替CheckedTextView

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
    getListView().setItemsCanFocus(false); 
    setListAdapter(new ArrayAdapter(this,R.layout.list_item,android.R.id.text1,COUNTRIES)); 

LIST_ITEM

<CheckedTextView 
     ..... 
     /> 

我想這樣
list_item_new

<LinearLayout> 
     ..... 
     <CheckedTextView/> 
     <TextView/> 
..... 
</LinearLayout> 

回答

0

如果您想自定義列表項出現的方式,你需要實現您自己的適配器。這比你想象的要簡單得多。這裏是你的基本代碼:

public class MyAdapter extends BaseAdapter { 
    List myData; 
    Context context; 

    public MyAdapter(Context ctx, List data) { 
     context = ctx; 
     myData = data; 
    } 

    public int getCount() { return myData.size(); } 

    public Object getItem(int pos) { return myData.itemAt(pos); } 

    public int getItemId(int pos) { return pos; } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     //this is where you create your own view with whatever layout you want 
     LinearLayout item; 
     if(convertView == null) { 
      //create/inflate your linear layout here 
      item = ...; 
     } 
     else { 
      item = (LinearLayout) convertView; 
     } 

     //now create/set your individual components inside your layout based on your element 
     //at the requested position 
     ... 
    } 
} 

而就是這樣。

+0

我不明白這是如何解決問題的。問題是LinearLayout中的CheckedTextView在按下時不會改變狀態? – 2012-05-23 05:27:15

+0

@GlennBech你試過這個嗎?我有 - 並且按需要工作。 – 2012-05-23 08:01:40

+0

我試圖使用一個帶CursorAdapter膨脹的嵌套checkedTextView的LinearLayout。這不起作用,這就是爲什麼我最終在這個頁面上。爲什麼應該使用自定義適配器?問題的根源在於LinearLayout沒有實現Checkable接口? (http://developer.android.com/reference/android/widget/Checkable.html) – 2012-05-23 09:21:32

相關問題