0

I make custom item for 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>

How change background color of LinearLayout in item programmatically?

I tried this:

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

But it is not working.

1 Answer 1

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;
        }
    }

use as

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

return defaul

 adapter.setColor(-1);
    adapter.notifyDataSetChanged();
2
  • мне предлагали так: hashcode.ru/questions/386983/… . Ваш способ не подойдёт, тк он не меняет цвет в самом слое с id listitem. А способ по ссылке не совсем работает
    – Perkovec
    Dec 28, 2014 at 19:29
  • замени проверку в адаптере if (color != -1){ LinearLayout listView = (LinearLayout) rootView.findViewById(R.id.listitem); listView.setBackgroundColor(color); } Dec 28, 2014 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.