将图像添加到Android ListView的简便方法

时间:2012-01-26 15:17:47

标签: android android-listview

我有一个lisview,我想要添加图像。我早期发现的示例使用simple_list_item_1显示,但似乎不允许我想要的内容。

如果可能的话,我也希望能够独立地改变物品的颜色。所以One的文字是红色,两个蓝色等等。

main.xml中:

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

    <TextView android:id="@+id/textHeader"
         android:textSize="24px"
         android:textColor="#006699"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content" 
         android:gravity="center_horizontal"
         />
    <ListView  
         android:id="@android:id/list"
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content"
         />
     <TextView android:id="@android:id/empty"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Empty set"
         />
<TextView
    android:id="@+id/status_text"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    />
</LinearLayout>

main.java

public class sGuide extends ListActivity {
    private String[] mBooks = new String[]{ "One", "Two", "Three" };


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayAdapter<String> booksAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mBooks);

        this.setListAdapter(booksAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mChecker.onDestroy();
    }
}

编辑:这是我的新行布局。我想这样做,以便点击行中的任何位置选择它,而不是点击图像或标签。

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4dp"
        android:src="@drawable/icon"
         >
    </ImageView>

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="11dp"
        android:layout_marginBottom="9dp"
        android:text="@+id/label"
        android:textSize="22dp" >
    </TextView>

</LinearLayout>

编辑2:更改线性布局以填充父级而不是换行文本。现在它有效。

2 个答案:

答案 0 :(得分:4)

对于这种行为,您需要实现自己的适配器。当您使用Arrayadapter时,您应该扩展Arrayadapter并覆盖getView方法,以您希望的方式更改ListItem的视图。有关此主题的更多信息,请查看此ListView Tutorial

答案 1 :(得分:2)

在这种情况下,您需要使用CustomAdapters,在getView()方法中执行您需要的内容,请参阅下面的链接以获取listview http://www.vogella.de/articles/AndroidListView/article.html

相关问题