user2955394 user2955394 - 3 months ago 32
Android Question

How to highlight android listview first item after load items to listview?

1.This is my listview

<ListView
android:id="@+id/lv_FromTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:listSelector="@drawable/list_selector"
android:orientation="vertical" />


2.in onCreate of main activity i load item and set adapter to listview

lv_FromTable = (ListView)rootView.findViewById(R.id.lv_FromTable);
FromTableAdapter = new ManageTableAdapter(context, FromTableList);
lv_FromTable.setAdapter(FromTableAdapter);
FromTableAdapter.notifyDataSetChanged();


3.i want to highlight on first item same click on listview item

4.i have already tried below code

lv_FromTable.performItemClick(lv_FromTable.getAdapter().getView(0, null, null), 0, lv_FromTable.getAdapter().getItemId(0));


it's raise onitemclick event but not highlight on first item.


  1. How to highlight android listview first item after load items to listview?


Answer
FromTableAdapter.setSelectedPosition(0); 
FromTableAdapter.notifyDataSetChanged();

Have getter and setter in adapter with selected position and use the variable and highlight the selected row in getView of adapter.

or

You're performing click right. In onItemClick, view.setSelected(true); but your drawable xml should have something like

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector> 

or

lv_FromTable.setItemChecked(0,true);

Edit : Don't forget, without the listSelector above wont work

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:listSelector="@drawable/list_selector_background" />