Rajat
Rajat

Reputation: 1447

Unable to highlight a selected row in ListView

This question has been asked a lot of times, and I am posting this question after reading around 20 posts and trying their various solutions in my code.

I have used a selector, and I have also defined choice mode of the ListView as ListView.CHOICE_MODE_SINGLE. But nothing works. Here is my xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="3"
    tools:context=".MainActivity" >

<ListView
    android:id="@+id/listView"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="@drawable/bg_key" />

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2" />

</LinearLayout>

Here is the java code for above file.

public class MainActivity extends Activity {

    ListView listView;
    TextView textView;

    String array[] = new String[] { "abc", "def", "ghi", "jkl",
            "mno", "pqr" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.listView);
        textView = (TextView) findViewById(R.id.textView);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(),
                android.R.layout.simple_dropdown_item_1line, array);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                view.setSelected(true);
                String clicked = array[position];
                textView.setText("You clicked " + clicked);

            }
        });

    }

And here is the bg_key.xml file stored in drawable folder.

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

    <item android:drawable="@color/pressed_color" android:state_selected="true"/>
    <item android:drawable="@color/default_color"/>

</selector>

The selected row still does not stay highlighted once it has been clicked. It is highlighted momentarily, but then it reverts back to the original color.

Please help.

Thanks

Upvotes: 0

Views: 132

Answers (1)

Menna-Allah Sami
Menna-Allah Sami

Reputation: 580

what about using listselector ?!

<listView
android:listSelector="@drawable/listview_selector"/>

Upvotes: 2

Related Questions