ashishduh
ashishduh

Reputation: 6699

Setting color of ListView items

I'm trying to individually set the color of certain ListView items like phone number and email address to blue, so that user knows they're clickable. Here's a snippet but implementing this doesn't work well at all, list items will randomly change colors when you scroll the list.

    List<Map<String, String>> data = new ArrayList<Map<String, String>>();

    //...add data to list

    SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.simple_list_item_2_custom, new String[] { LABEL, VALUE },
        new int[] { R.id.text1, R.id.text2 })
    {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) 
        {
            LinearLayout view = (LinearLayout)super.getView(position, convertView, parent);

            String label = data.get(position).get(LABEL);

            if (label.equals("Email Address"))
            {
                ((TextView)view.getChildAt(0)).setTextColor(Color.BLUE);
            }

            return view;
        }
    };

And here's the LinearLayout that defines a list item:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:orientation="vertical" >
    <TextView android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="?android:attr/listPreferredItemPaddingStart"
        android:layout_marginTop="8dip"
        android:textAppearance="?android:attr/textAppearanceSmall" />
    <TextView android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@android:id/text1"
        android:textAppearance="?android:attr/textAppearanceListItem" />
</LinearLayout>

Upvotes: 1

Views: 160

Answers (1)

Pozzo Apps
Pozzo Apps

Reputation: 1857

You missed the else of "if (label.equals("Email Address"))"

You have to place another text color when it is not an email address, like this: ((TextView)view.getChildAt(0)).setTextColor(Color.WHITE);

The reason is cause Android adapter reuses the old line which is no long being displayed, in this case the one you already defined to blue.

Upvotes: 1

Related Questions