2011-07-28 49 views
0

我想構建一個具有checkBox,Textview和圖像的ListView,並且這應該作爲可滾動列表在行中重複。自定義適配器問題。

我跟着Android hello-listview tutorial但是當我定製的XML文件得到一個錯誤,並引用它:

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

我肯定,我需要一個自定義適配器,可以在各行中放置每個國家名稱,但無法理解如何去做。你能幫我解決嗎?非常感謝。

+0

太模糊了,相反,嘗試詢問您在嘗試實現所述自定義適配器時遇到的具體挑戰。 – dmon

回答

0

以下是您需要創建具有多個數據段的自定義ListView行的高級步驟。

  1. 創建一個類來容納每行所需的數據。在這種情況下,它似乎是一個布爾值,一個字符串,並繪製或繪製的ID。我們稱這個類爲Foo。
  2. 爲您的列表行自定義佈局xml文件(如refrerenced下面custom_list_layout)
  3. 創建一個名爲FooAdapter定製的適配器,將在它的構造FOOS的列表。

  4. 在FooAdapter的getView()方法中,您將爲此行充氣自定義視圖,按ID查找所有元素,並用Foo中的數據填充它們。事情是這樣的:

    公共類FooAdapter擴展ArrayAdapter {

    private List<Foo> foos; 
    
    public FooAdapater(Context ctx, int textViewResourceId, ArrayList<Foo> items) { 
        super(ctx, textViewResourceId, items); 
        this.foos = items; 
    } 
    
    @Override 
    public View getView(int pos, View view, ViewGroup parent) { 
        final LayoutInflater inflater = parent.getLayoutInflater(); 
        final View entry = inflater.inflate(R.layout.custom_list_layout, null); 
        Foo foo = foos.get(position); 
        TextView tv = (TextView) entry.findViewById(R.id.custom_layout_text_view); 
        tv.setText(foo.getTitle()); 
         // do the same for the checkbox and image 
        return v; 
    } 
    

    }

  5. 最後,在活動實例化這個適配器,而不是 「新ArrayAdapter」 通過在列表中。