2012-04-04 72 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

相关问题