63024

android ListView Style and colors?

Question:

i have problem styling my listview from selector.xml items style ( background )

the colors not switched its show all the items black , i want to switch items colors between black and white , for now aim switching items colors from listview Adapter, but when i switch items colors from listview Adapter when i click on any item the item background become blue !

here is my code

public class Home_ForumsList_listview extends ArrayAdapter<Object>{ private int[] colors = new int[] { 0x30ffffff, 0x30808080 }; Context context; private LayoutInflater mInflater; @SuppressWarnings("rawtypes") ArrayList ob; int resource ; /*================================================ * Setup ListView *===============================================*/ @SuppressWarnings("unchecked") public Home_ForumsList_listview (Context context, int resource, @SuppressWarnings("rawtypes") ArrayList objects) { super(context, resource,objects); this.context = context; this.ob = objects; this.resource = resource; mInflater = LayoutInflater.from(context); } /*================================================ * Items Counter *===============================================*/ public int getCount() { return ob.size(); } /*================================================ * Item Posistion JSON *===============================================*/ public JSONObject getItem(JSONObject position) { return position; } /*================================================ * Item Position *===============================================*/ public long getItemId(int position) { return position; } /*================================================ * Hold Views inside Chant Bit View *===============================================*/ static class ViewHolder { TextView forum_title; TextView forum_desc; TextView forum_catagories; TextView forumcode; Button popup_but_id; RatingBar ratingsmall; } /*================================================ * Setup Each View raw by raw *===============================================*/ public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; JSONObject r = (JSONObject) getItem(position); if(convertView == null) { convertView = mInflater.inflate(R.layout.a_home_forumslist_bit, null); holder = new ViewHolder(); convertView.setTag(holder); holder.forum_title = (TextView) convertView.findViewById(R.id.flist_forum_title); holder.forum_desc = (TextView) convertView.findViewById(R.id.flist_forum_desc); holder.forum_catagories = (TextView) convertView.findViewById(R.id.flist_forum_catagories); holder.forumcode = (TextView) convertView.findViewById(R.id.flist_forumcode); holder.ratingsmall = (RatingBar) convertView.findViewById(R.id.ratingsmall); } else { holder = (ViewHolder) convertView.getTag(); } int colorPos = position % colors.length; convertView.setBackgroundColor(colors[colorPos]); try { holder.forum_title.setText(r.getString("forum_title")); if ( r.getString("forum_desc").equals("")) { holder.forum_desc.setVisibility(View.GONE); } float z = (float) r.getInt("rate"); holder.ratingsmall.setRating(z); holder.forum_desc.setText(r.getString("forum_desc")); holder.forumcode.setText( context.getString(R.string.forumcode) + " : ( "+ r.getLong("forumcode") + " ) "); holder.forum_catagories.setText( " : " + r.getString("forum_catagories")); } catch (JSONException e) { e.printStackTrace(); } return convertView; } }

i googled it how to style listview , all the examples showing same colors switch from Adapter , is there any way to style listview items from selector.xml ?

sorry for my bad English ^_^ i hope you got it

Answer1:

It sounds like you want to alternate background colors in your list, so item 0 is white, item 1 is black, item 2 is white, etc.

First, define your colors as Android resources:

res/colors.xml:

<?xml version="1.0" encoding="utf-8"?> <resources> <color name="white">#ffffff</color> <color name="black">#000000</color> </resources>

Then, use these resource identifiers as the backgrounds. Right now, you're giving it the color hex as an int, which is wrong -- it expects an int that is a resource identifier. Like this:

private int[] colors = new int[] { R.color.white, R.color.black };

That should work. Try it out.

To get rid of the blue highlight, you could make selectors and use those instead of just black and white:

drawable/dark_selector.xml

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/gray" android:pressed="true" /> <item android:color="@color/black" /> </selector>

Then use the drawables as your backgrounds.

private int[] colors = new int[] { R.drawable.lightSelector, R.drawable.darkSelector };

Answer2:

I have two thought here:

Maybe you forget to set to transparent the <a href="http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:cacheColorHint" rel="nofollow">cache color hint</a> of the ListView, you can see <a href="https://stackoverflow.com/questions/2833057/background-listview-becomes-black-when-scrolling" rel="nofollow">this answer</a>.

android:cacheColorHint="@android:color/transparent"

Or maybe you need to set the <a href="http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:scrollingCache" rel="nofollow">scrolling cache</a> on your ListView to false.

android:scrollingCache="false"

PD: it could be useful is you post your XML layout.

Answer3:

If you just want to alternate color of line in your listView, you can use a normal listView with an BaseAdapter of your choice.

Take a look a it :

package com.example.joignabilite; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; public class ContactAdapter extends BaseAdapter { // Une liste de Contacts private List<Contact> mListP; // Le contexte dans lequel est présent notre adapter private Context mContext; // Un mécanisme pour gérer l'affichage graphique depuis un layout XML private LayoutInflater mInflater; private int white = 0xFFFFFFFF; private int grey = 0x33000000; public ContactAdapter(Context context, List<Contact> aListP) { mContext = context; mListP = aListP; mInflater = LayoutInflater.from(mContext); } public int getCount() { return mListP.size(); } public Object getItem(int position) { return mListP.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { LinearLayout layoutItem; // (1) : Réutilisation des layouts if (convertView == null) { // Initialisation de notre item à partir du layout XML // "Contact_layout.xml" layoutItem = (LinearLayout) mInflater.inflate( R.layout.item_contact, parent, false); } else { layoutItem = (LinearLayout) convertView; } // (2) : Récupération des TextView de notre layout TextView tv_Nom = (TextView) layoutItem .findViewById(R.id.repertoire_item); // (3) : Renseignement des valeurs tv_Nom.setText(mListP.get(position).nom); // On mémorise la position de la "Contact" dans le composant textview tv_Nom.setTag(position); /* * Here is the way to change color using pair and unpair line */ if (position % 2 == 0) layoutItem.setBackgroundColor(grey); else layoutItem.setBackgroundColor(white); // On ajoute un listener tv_Nom.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Lorsque l'on clique sur le nom, on récupère la position du // "Contact" Integer position = (Integer) v.getTag(); // On prévient les listeners qu'il y a eu un clic sur le // TextView "TV_Nom". sendListener(mListP.get(position), position); } }); // On retourne l'item créé. return layoutItem; } /** * Interface pour écouter les évènements sur le nom d'une Contact */ public interface ContactAdapterListener { public void onClickNom(Contact item, int position); } // Contient la liste des listeners private ArrayList<ContactAdapterListener> mListListener = new ArrayList<ContactAdapterListener>(); /** * Pour ajouter un listener sur notre adapter */ public void addListener(ContactAdapterListener aListener) { mListListener.add(aListener); } private void sendListener(Contact item, int position) { for (int i = mListListener.size() - 1; i >= 0; i--) { mListListener.get(i).onClickNom(item, position); } } }

Recommend

  • android ListView Style and colors?
  • UI get value function not work in Document App
  • How to set individual segment color in uisegmentedcontrol?
  • How to detect the imageview of clicked position in Gridview?
  • Android Custom Adapter Filter not working
  • How to get the Drawable name from imageview in android and get it's String name for comparing
  • picasso - load image into imagebutton in adapter
  • Gif not animated in custom listview
  • How show tag of button?
  • onDestroy doesn't work
  • BitmapFactory.decodeStream throwing NetworkOnMainThreadException - Android
  • Buttons in ListView each item layout
  • OutOfMemoryError in my gridAdapter
  • How to set radio button to checked when i click on list item
  • Android theme not affecting TextViews inside list item
  • Get Text from TextView -w/Button in custom ListView
  • Navigation Drawer list items hide/go invisible on scroll
  • SpannableString - setTag
  • Adding properties to UIControls without subclassing
  • Android ListView with toggle button
  • Custom UITableViewCell in UISearchDisplayController
  • Accessing an Object from Class type(+) method in iPhone & Cocos2d?
  • List view crashes when scrolling “The application may be doing too much work on its main thread.”
  • Listview with multiple strings
  • Eventbus onMessageEvent not getting called
  • How to Handle Click on Imageview in Custom Listview with image and Textview?
  • Android: How do you create an EditText field in java class
  • CloseOptionsMenu doesn't work?
  • Unable to resolve Static method?
  • Activity overlaying. WindowManager.LayoutParams
  • Syntax error on tokens, AnnotationName expected instead - error on query
  • WPF version of .ScaleControl?
  • Android Activity.onWindowFocusChanged doesn't get called from within TabHost
  • jquery mobile loadPage not working
  • align graphs with different xlab
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How to stop GridView from loading again when I press back button?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize