2012-04-24 50 views
6

Tengo un ListView y quiero cambiar el Backgroundcolor del mismo. Debería ir así. 1.Item = gris; 2. Artículo; blanco; 3. Artículo = gris; 4. Elemento = blanco, etc. Por lo tanto, debe tener 2 colores de fondo. Intento archivar eso por casi 2 horas. Me estoy confundiendo No puedo levantarme con una Solución. Espero que alguien de ustedes pueda ayudarme.Android - ListView con 2 colores diferentes

he probado con:

for(int counter = 0; counter < itemList.size(); counter++){ 
      if(adapter.getItem(position) %2 == 1){ 
       Layout.setBackgroundColor(Color.GREY) 
        }; 
      else{ 
      Layout.setBackgroundColor(Color.WHITE); 
       } 

Así que aquí es mi código agujero. Espero que alguien de ustedes me puede decir:

MainActivity

public class MainActivity extends Activity implements OnItemClickListener { 

    ListView lview3; 
    ListViewCustomAdapter adapter; 
    private ArrayList<Object> itemList; 
    private ItemBean bean; 

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

     prepareArrayLits(); 
     lview3 = (ListView) findViewById(R.id.listView1); 
     adapter = new ListViewCustomAdapter(this, itemList); 
     lview3.setAdapter(adapter); 




     lview3.setOnItemClickListener(this); 
    } 

    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { 
     // TODO Auto-generated method stub 
     RelativeLayout Layout = (RelativeLayout) findViewById(R.id.relativeLayout1); 
     ItemBean bean = (ItemBean) adapter.getItem(position); 
     for(int counter = 0; counter < itemList.size(); counter++){ 
      adapter.getItem(position); 
      Layout.setBackgroundColor(Color.CYAN);} 

     Toast.makeText(this, "Title => "+bean.getTitle()+" \n Description => "+bean.getDescription(), Toast.LENGTH_SHORT).show(); 
    } 

    /* Method used to prepare the ArrayList, 
    * Same way, you can also do looping and adding object into the ArrayList. 
    */ 
    public void prepareArrayLits() 
    { 
     itemList = new ArrayList<Object>(); 

     AddObjectToList(R.drawable.ic_add, "add", "Add desc", "2"); 
     AddObjectToList(R.drawable.ic_delete, "Delete", "Delete desc", "2"); 
     AddObjectToList(R.drawable.ic_down, "Down", "Down desc", "2"); 
     AddObjectToList(R.drawable.ic_info, "Information", "Information desc", "2"); 
     AddObjectToList(R.drawable.ic_help, "Help", "Help desc", "2"); 
     AddObjectToList(R.drawable.ic_download, "Download", "Download desc", "2"); 
     AddObjectToList(R.drawable.ic_mail, "Mail", "Mail desc", "2"); 
     AddObjectToList(R.drawable.ic_search, "Search", "Search desc", "2"); 
     AddObjectToList(R.drawable.ic_settings, "Settings", "Settings desc", "2"); 

    } 

    // Add one item into the Array List 
    public void AddObjectToList(int image, String title, String desc, String duration) 
    { 

     bean = new ItemBean(); 
     bean.setduration(duration); 
     bean.setDescription(desc); 
     bean.setImage(image); 
     bean.setTitle(title); 
     itemList.add(bean); 
    } 



} 

ItemBean

public class ItemBean 
{ 
    String title; 
    String description; 
    int image; 
    String duration; 

    public String getTitle() { 
     return title; 
    } 
    public String getDuration() { 
     return duration; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 

    public String getDescription() { 
     return description; 
    } 

    public void setDescription(String description) { 
     this.description = description; 
    } 

    public int getImage() { 
     return image; 
    } 

    public void setImage(int image) { 
     this.image = image; 
    } 

    public void setduration(String duration) { 
     this.duration = duration; 
    } 
} 

ListViewCustomAdapter

public class ListViewCustomAdapter extends BaseAdapter{ 

    ArrayList<Object> itemList; 

    public Activity context; 
    public LayoutInflater inflater; 

    public ListViewCustomAdapter(Activity context,ArrayList<Object> itemList) { 
     super(); 

     this.context = context; 
     this.itemList = itemList; 

     this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    public int getCount() { 
     // TODO Auto-generated method stub 
     return itemList.size(); 
    } 

    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return itemList.get(position); 
    } 

    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return 0; 
    } 

    public static class ViewHolder 
    { 
     ImageView imgViewLogo; 
     TextView txtViewTitle; 
     TextView txtViewDescription; 
     TextView duration; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     // TODO Auto-generated method stub 

     ViewHolder holder; 
     if(convertView==null) 
     { 
      holder = new ViewHolder(); 
      convertView = inflater.inflate(R.layout.items, null); 

      holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo); 
      holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle); 
      holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescription); 
      holder.duration = (TextView) convertView.findViewById(R.id.duration); 

      convertView.setTag(holder); 
     } 
     else 
      holder=(ViewHolder)convertView.getTag(); 

     ItemBean bean = (ItemBean) itemList.get(position); 

     holder.imgViewLogo.setImageResource(bean.getImage()); 
     holder.txtViewTitle.setText(bean.getTitle()); 
     holder.txtViewDescription.setText(bean.getDescription()); 
     holder.duration.setText(bean.getDuration()); 



     return convertView; 
    } 

} 

Disposición XML: * artículos *

<RelativeLayout  android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/list_selector" xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dip"> 

    <ImageView 
     android:layout_width="50dip" 
     android:layout_height="50dip" 
     android:padding="3dip" 
     android:id="@+id/imgViewLogo" 
     android:src="@drawable/icon" 
     android:layout_alignParentLeft="true" 
     android:layout_centerInParent="true" 
     android:background="@drawable/image_bg" 
     android:layout_marginRight="5dip" 
     android:scaleType="center" 
     > 
    </ImageView> 

    <TextView 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:layout_height="wrap_content" 
     android:layout_alignTop="@+id/imgViewLogo" 
     android:text="TextView" 
     android:layout_width="wrap_content" 
     android:id="@+id/txtViewTitle" 
     android:layout_toRightOf="@+id/imgViewLogo" 
     android:textColor="#040404" 
     android:typeface="sans" 
     android:textSize="20dip" 
     android:textStyle="bold" 
     android:layout_marginRight="15dp" 
     > 
    </TextView> 

    <TextView 
     android:layout_height="wrap_content" 
     android:text="TextView" 
     android:layout_width="wrap_content" 
     android:id="@+id/txtViewDescription" 

     android:textColor="#343434" 
     android:textSize="15dip" 
     android:layout_marginTop="1dip" 
     android:layout_toRightOf="@+id/imgViewLogo" 
     android:layout_below="@+id/txtViewTitle" 
     android:layout_marginLeft="2dip" 
     android:layout_marginRight="15dp" 
     > 
    </TextView> 
    <TextView 
     android:id="@+id/duration" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_alignTop="@+id/txtViewTitle" 
     android:gravity="right" 
     android:layout_marginRight="5dip" 
     android:textSize="15dip" 
     android:textColor="#10bcc9" 
     android:textStyle="bold"/> 

    <ImageView android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/arrow" 
     android:layout_alignParentRight="true" 
     android:layout_centerVertical="true" 

     /> 

</RelativeLayout> 

Diseño: * principal *

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 


    > 


    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:divider="#b5b5b5" 
     android:dividerHeight="1dp" 
     android:listSelector="@drawable/list_selector" 
     /> 



</LinearLayout> 

cada consejo sería de gran ayuda, gracias .

Respuesta

10

No utilice ese lazo for para establecer el color de fondo después del hecho. Hágalo en su método getView de su adaptador. Pruebe esto:

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

    /* remainder is unchanged */ 

    convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.GREY); 
    return convertView; 
} 
+0

Estuve fuera por una semana, así que no pude probarlo. Ahora estoy confundido sobre cómo configurarlo. ¿Me puedes ayudar? ¿Debo llamar a getView() en mi oncreate? ¿Y qué parámetro debería insertar? Gracias – Ahmad

0

Puede hacerlo fácilmente configurando el fondo dentro de la función getView de su adaptador personalizado.

probar este código:

if(position % 2 == 0) 
      convertView.setBackgroundColor(Color.GREY); 
    else 
      convertView.setBackgroundColor(Color.WHITE); 
0

Usted puede devolver diferentes puntos de vista de getView en base a la aprobada en posición de elemento.

-1

Creo que se puede hacer esto en base a la posición

 if (position == 0) 
     { 
      view.SetBackgroundColor(Android.Graphics.Color.gray); 
     } 
     else if (position == 1) 
     { 
      view.SetBackgroundColor(Android.Graphics.Color.white); 
     } 

y así sucesivamente dependiendo del número de posiciones que tiene.

3

Esta es otra forma de cambiar el fondo utilizando el selector de selector. Al usar este método, se conservarán los colores de desplazamiento y enfoque del selector.

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

    /* remainder is unchanged */ 

    convertView.setBackgroundResource(position % 2 == 0 ? R.drawable.list_selector_first : R.drawable.list_selector_second); 
    return convertView; 
} 
Cuestiones relacionadas