2012-03-03 48 views
1

我有一個要求,我必須生成一個列表視圖,每行有一個圖標和一個名稱。代碼看起來像這樣。列表視圖顯示的對象,而不是行在android

public class MyListActivity extends ListActivity { 
... 
... 

    ArrayList<StringBuilder> categories = new ArrayList<StringBuilder>(); 
    categories.add(new StringBuilder("xyaq")); 
    categories.add(new StringBuilder("wers")); 
    categories.add(new StringBuilder("test2")); 
    categories.add(new StringBuilder("asfda")); 
    categories.add(new StringBuilder("hoyio")); 

    ArrayList<RelativeLayout> departments = new ArrayList<RelativeLayout>(); 

    for (StringBuilder category : categories) { 
     RelativeLayout categoryRow = (RelativeLayout) mInflater.inflate(
       R.layout.products_row, null); 

     ImageView tempImage = (ImageView) categoryRow.getChildAt(0); 
     tempImage.setBackgroundResource(R.drawable.ic_launcher); 
     TextView tempTextView = (TextView) categoryRow.getChildAt(1); 
     tempTextView.setText(category); 
     departments.add(categoryRow); 
    } 
    ArrayAdapter<RelativeLayout> departmentAdaptor = new ArrayAdapter<RelativeLayout>(
      this, android.R.layout.simple_list_item_1, departments); 

    setListAdapter(departmentAdaptor); 
} 

和products_row.xml如下:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" > 

<ImageView 
    android:id="@+id/deptIcon" 
    android:layout_width="64dp" 
    android:layout_height="64dp" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:background="#FFFFFF" 
    android:clickable="false" 
    android:contentDescription="@string/hello" 
    android:scaleType="fitXY" /> 

<TextView 
    android:id="@+id/deptName" 
    android:layout_width="fill_parent" 
    android:layout_height="54dp" 
    android:layout_alignLeft="@id/deptIcon" 
    android:layout_marginLeft="80dp" 
    android:gravity="left|center" 
    android:textSize="25dp" 
    android:textStyle="bold" /> 

</RelativeLayout> 

我現在面臨的問題是我無法看到的圖像和相應的文本行。相反,它會顯示相對佈局對象的列表。

回答

1

這不是一個正確的方法來做你正在努力實現的。 您需要爲此創建自定義適配器。

看到這個鏈接,查看我的回答: Listview with Image,Text and Checkbox

有整個活動代碼,幷包含擴展ArrayAdapte一個內部類MyAdapter。

+0

非常感謝@Pankaj。創建一個自定義適配器有訣竅!但我很想知道爲什麼我的實現方式(將列表行的ArrayList傳遞給arrayadapter)工作? :-) – 2012-03-04 16:48:25

+0

它不會自動將ArrayList的相對值分配給我們的listview。我們必須手動將數據分配給組件。這就是listview的工作方式 – Pankaj 2012-03-05 14:50:37

+0

Oh..ok。得到它了。非常感謝你的澄清。 – 2012-03-05 15:50:39

相關問題