Zyyk Savvins
Zyyk Savvins

Reputation: 493

Android ListView Persistent Background

My question is this: Is it possible to apply a drawable resource to a TextView in a ListView, that makes it keep its background color, after the user lifts his/her finger ofF said TextView?

Consider:

  1. The user selects an item in a ListView
  2. The list item highlights
  3. The user removes his/her finger off the item
  4. The item is no longer highlighted

My question is, is it possible to make allow the object to remain highlighted at step 4 ? Im currently using a state list drawable for my list items. I've tried

android:state_focused="true"

android:state_selected="true"

android:state_check="true"

Thanks in advance :)

Edit

Solved. I achieved this through java code. For those interested, I did the following:

Declared an integer variable, 'previous', to store the previous index, starting at 0 for the first item, and force highlighted it through setBackground().

Then, in the onItemClickListener for the list, I simply clear the highlight of the previous item, highlight the current, and set 'previous' to the index of the currently selected item.

Don't know how I didn't think of this before xD I'm usually good at problem solving.

Happens to all of us at some point i guess :P

Upvotes: 4

Views: 508

Answers (1)

Kumar Bibek
Kumar Bibek

Reputation: 9117

Although your approach would work, it's extra pieces of code which I would like to avoid. The steps to achieve this are as follows:

Make the list view's selection mode to singleChoiceMode.

Make this selector

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

    <item android:drawable="@color/color_light_blue_for_selected_item" android:state_checked="true"/>

</selector>

Set this as the background of your list items.

And it should work.

Upvotes: 1

Related Questions