codie4711
codie4711

Reputation: 798

Set a background color to a selected ListView Item in android

I have a listview which displays several items. Now I want to scroll to some specific item (e.g. the 33th item). I know that this can be done via

myList.setSelection(32);

But on the UI the item doesn't receive any highlighting (because it is in touch mode?!). How can I apply a specific background color for this item? I tried

myList.getSelection().getSelectedView().setBackgroundColor(Color.Red);

but i get a NullPointerException because getSelectedView() returns null. Is there a way to achieve this highlighting? I have to notify the user somehow about which item is the "active" one...

Upvotes: 14

Views: 34684

Answers (7)

Sagar Maiyad
Sagar Maiyad

Reputation: 12733

ListView in xml file:

<ListView android:id="@+id/android:list" android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_below="@+id/Tablayoutdesign"
        android:cacheColorHint="#000000"
        android:dividerHeight="1dip"
        android:layout_marginTop="63dip"
        android:layout_marginBottom="40dip"

        />

Create new xml with listselector name like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

  <!-- Selected --> 
  <item 
    android:state_focused="true" 
    android:state_selected="false" 
    android:drawable="@drawable/focused"/> 

  <!-- Pressed -->
  <item 
    android:state_selected="true" 
    android:state_focused="false"
    android:drawable="@drawable/selected" /> 

</selector>

Create colors.xml file like:

<resources>
    <drawable name="focused">#ff5500</drawable>
    <drawable name="selected">#FF00FF</drawable>
</resources>

In your java code:

ListView lv= (ListView) findViewById(R.id.list);
lv.setSelector( R.drawable.listselector);

Upvotes: 1

atulkhatri
atulkhatri

Reputation: 11333

Try this, it will work-

myList.getChildAt(myList.getSelectedItemPosition()).setBackgroundColor(Color.RED);

Upvotes: 3

The nullPointerException is probably because you're in touchmode, setSelection doesn't really selects the item on the listView when you're in touch mode, it just "looks" at it, if you know what i mean.

You Gotta do a customized Adapter (by creating a class that extends the adapter you're currently using :] )

And at your custom adapter class you must override the getView(int position, View convertView, ViewGroup parent) method, like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null)
        convertView = inflater.inflate(android.R.layout.simple_list_item_1, null);
    String content = lista.get(position).toString();
    TextView text = (TextView) convertView.findViewById(android.R.id.text1);
    text.setText(content);
    convertView.setBackgroundColor(lista.get(position).getBackgroundColor());
    return convertView;
}

In the code, the variable "lista" is a list of some items i have on my adapter.

So, when you're done selecting your item, you gotta call the getView for every item you have, or you can call the method invalidateViews from your listView before you set the selection (if you call invalidateViews after the selection, the selection will be ignored (at least on touchmode :] ))

Upvotes: 0

vqtr
vqtr

Reputation: 115

  1. To highlight the selected item, you should request focus for the listView and run setSelection() in the UI thread. This worked for me:
runOnUiThread(new Runnable() {
    public void run() {
        myList.requestFocus();
        myList.setSelection(position);
    }
});

2.To apply a specific color to an item. You can use customized listItem.

a. Set customized lisItem for your listView:

ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.customizedlistitem,arrListView);
myList.setAdapter(listAdapter);

b. In your layout folder, create customizedlistitem.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@+id/customizedlistitem"   
    android:layout_width="match_parent"   
    android:layout_height="wrap_content"
    android:background="@drawable/customizedbackground"/>   

c. In your drawable folder, create customizedbackground.xml like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:state_pressed="false" android:drawable="@color/RED"></item>
    <item android:state_pressed="true" android:drawable="@color/GREEN"></item>      
    <item android:drawable="@color/BLACK"></item>   <!-- for other state -->        
</selector>

d. Make sure color RED, GREEN and BLACK was defined in your project (you can define it in color.xml under values folder):

<?xml version="1.0" encoding="utf-8"?>

<resources>  
     <color name="RED">#FF0000</color>
     <color name="GREEN">#008000</color>
     <color name="BLACK">#000000</color>
</resources>

Upvotes: 3

Yajneshwar Mandal
Yajneshwar Mandal

Reputation: 943

I tried by the following way and solved the problem.

Created a javaBean class that receives the position. Like following.

public class Global {

    public static int mListPosition = 0;

    public static int getListPosition() {
        return mListPosition;
    }

    public static void setListPosition(int mListPosition) {
        Global.mListPosition = mListPosition;
    }
}

Then from The OnListItemClickListener() I set the position of the selected item. Like following

mList.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Global.setListPosition(arg2);                   
    }
});

Then in the adapter class do the following

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater) mCtx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.details_retailer_list_row, null);

        mHolder = new ViewHolder();
        v.setTag(mHolder);

        mHolder.mDetailsRetailerLayout = (LinearLayout) v
                .findViewById(R.id.details_cart_retailer_row_layout);
        mHolder.mDetailsRetailer = (TextView) v
                .findViewById(R.id.detailsRetailerRow);

    } else {
        mHolder = (ViewHolder) v.getTag();
    }

    final CartDetailsRetailerBean mDetailsRetailerBean = mItems
            .get(position);
    if (position == Global.getListPosition()) {
        mHolder.mDetailsRetailerLayout
                .setBackgroundResource(R.drawable.image1);
    } else {
        mHolder.mDetailsRetailerLayout
                .setBackgroundResource(R.drawable.image2);
    }

    if (mDetailsRetailerBean != null) {
        Log.i("Global Position", "" + Global.getListPosition());
        mHolder.mDetailsRetailer.setText(mDetailsRetailerBean
                .getRetailerName());
    }
    return v;
}    

Try this one to change the Selected row background color change in Android List view.

Upvotes: 0

Jaydeep Khamar
Jaydeep Khamar

Reputation: 5985

Change the line

myList.getSelection().getSelectedView().setBackgroundColor(Color.Red);

to

myList.getSelectedView().setBackgroundColor(getResources().getColor(Color.RED));

Upvotes: 0

Mark Allison
Mark Allison

Reputation: 21909

Probably the easiest way is to use a State List Drawable for your background. This enables you to apply different styles depending on whether the control in question is selected / focused / disabled / etc.

For an introduction to State List Drawables, have a look at this article.

Upvotes: 0

Related Questions