如何在ListView中更改自定义项?

时间:2014-12-28 18:50:02

标签: java android listview

我为ListView制作自定义项目:

adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, constants);
lv.setAdapter(adapter);

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listitem"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4d73ff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/product_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:minHeight="48dp"
        android:padding="10dp"
        android:textColor="#fff"
        android:textSize="16sp" />

</LinearLayout>

如何以编程方式更改LinearLayout项目的背景颜色?

我试过了:

for (int i=0; i<constants.size(); i++){
    lv.getChildAt(i).setBackgroundColor(Color.argb(255, 255, 0, 0));
}

但它没有用。

1 个答案:

答案 0 :(得分:0)

class MyAdapter extends ArrayAdapter{

        private int color;

        MyAdapter(Context context, int resource, int textViewResourceId, List objects) {
            super(context, resource, textViewResourceId, objects);
            color = -1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rootView = super.getView(position, convertView, parent);
            if (color != -1){
                rootView.setBackgroundColor(color);
            }
            return rootView;
        }

        public void setColor(int color) {
            this.color = color;
        }
    }

用作

adapter.setColor(Color.argb(255, 255, 0, 0));
adapter.notifyDataSetChanged();

返回默认值

 adapter.setColor(-1);
    adapter.notifyDataSetChanged();