为每个项目设置drawable listview背景

时间:2012-04-13 09:13:28

标签: android listview custom-lists

我有黑色背景的默认列表视图,我想这样:

enter image description here

或:

enter image description here

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

如果使用数组适配器,则应创建两个布局。在其中一个中定义listview元素的视图,另一个必须包含<listview>标记。

on onCreate:

public class ListAction extends Activity {
    private ListView lv1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        lv1 = (ListView) findViewById(R.id.listView);

            ArrayAdapter<CharSequence> adapter = ArrayAdapter
                    .createFromResource(this, some array,
                            R.layout.list_items);
            lv1.setAdapter(adapter);
            cats = getResources().getStringArray(some array);

        lv1.setTextFilterEnabled(true);
        lv1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> a, View v, int position,
                    long id) {

            }
        });
    }
}

您使用R.array.<name>代替some array

list_item.xml示例:

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:paddingBottom="8.0dip"
        android:paddingLeft="12.0dip"
        android:paddingRight="3.0dip"
        android:paddingTop="8.0dip"
        android:textColor="#ffffffff"
        android:textSize="10.0pt"
        android:textStyle="italic"
        android:background="@drawable/list_bg"
        android:text="List Item" />

list.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"
    android:background="@color/white" >

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:divider="@drawable/divider" />

</LinearLayout>

有关更具体的布局,您可以查看此链接http://www.ezzylearning.com/tutorial.aspx?tid=1763429&q=customizing-android-listview-items-with-custom-arrayadapter


<强>加了: 首先,您可以在list.xml中更改整个布局的背景,也可以使用自定义分隔符(您应该使用上面的标记divider)。

您无法在list_item.xml中添加其他布局,但可以使用android:background来设置项目背景。我从来没用过,但我知道它有效。要进行更多更改,您应该使用simplearray或编写自己的适配器。

示例如何使用渐变(我将它用于按钮):

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners android:radius="12px" />
    <gradient
        android:angle="90"
        android:endColor="#color2"
        android:startColor="#color1"
        android:type="linear" />
</shape>
相关问题