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

2024-02-27

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

如果可能的话,我还希望能够独立地更改项目的颜色。所以“一”的文本是红色,“二”是蓝色,等等。

主要.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:更改线性布局以填充父级而不是换行文本。现在可以了。


对于这种行为,您需要实现自己的适配器。当您使用 Arrayadapter 时,您应该扩展 Arrayadapter 并覆盖 getView 方法,以按照您想要的方式更改 ListItem 的视图。看看这个列表视图教程 http://www.vogella.de/articles/AndroidListView/article.html#ownadapter有关此主题的更多信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将图像添加到 Android ListView 的简单方法 的相关文章

随机推荐