2014-12-28 3 views
0

Я сделать пользовательский элемент для 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)); 
} 

Но это не работает.

ответ

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(); 

возвращение defaul

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

мне предлагали так: http://hashcode.ru/questions/386983/java-%D1%81%D0%BC % D0% B5% D0% BD% D0% B0-% D0% B2% D0% B8% D0% B4% D0% B0-% D0% BA% D0% B0% D1% 81% D1% 82% D0% BE % D0% BC% D0% BD% D0% BE% D0% B3% D0% BE-item-% D0% B2-listview. Ваш способ не подойдёт, тк он не меняет цвет в самом слое с id listitem. (0) – Perkovec

+0

замените проверку в адаптере 'if (color! = -1) { LinearLayout listView = (LinearLayout) rootView.findViewById (R.id.listitem); listView.setBackgroundColor (цвет); } ' – SorryForMyEnglish

+0

и у вас уформа бэк прозрачный – SorryForMyEnglish

Смежные вопросы