如何在ListView上设置背景

时间:2014-09-12 14:02:58

标签: android listview background set

我想在链接的图片中设置我的列表视图的背景,它应该显示为按钮,但我不能单独设置背景。

http://www.delta.edu/images/OIT/Android%20List%20View.png

我已经尝试android:listSelector="@drawable/pic"这对我没用。

我也尝试了tools:listitem="@layout/row",但它对我没用。

我希望我能清楚我的问题。

1 个答案:

答案 0 :(得分:0)

查看tutorial like this以获取一些提示。

在drawable中创建一个类似于这样的XML文件:

<强> rounded_corners.xml

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

    <solid android:color="#00FF00"/>

    <corners android:radius="5dp" />

    <padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />

    <stroke android:width="3dp" android:color="#00CC00"/>
</shape>

<强> listview_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/rounded_corner" android:state_enabled="true"/>

    <item android:drawable="@drawable/rounded_corner" android:state_pressed="true"/>

    <item android:drawable="@drawable/rounded_corner" android:state_focused="true"/>

</selector>

将它应用于ListView适配器,类似于:

public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    PlanetHolder holder = new PlanetHolder();

    // First let's verify the convertView is not null
    if (convertView == null) {
        // This a new view we inflate the new layout
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.row_layout, null);
        // Now we can fill the layout with the right values
        TextView tv = (TextView) v.findViewById(R.id.name);

        holder.planetNameView = tv;

        v.setTag(holder);

        v.setBackgroundResource(R.drawable.rounded_corner);
    }
    else 
        holder = (PlanetHolder) v.getTag();

    Planet p = planetList.get(position);
    holder.planetNameView.setText(p.getName());

    return v;
}