vxh.viet
9/7/2017 - 3:55 AM

Highlight item in ListView.

Highlight item in ListView.

Source: StackOverflow, StackOverflow

Question: How to highlight ListView item by touch and by code?

Answer:

ListView mListView;
private ArrayList<String> mList = new ArrayList<>();
private ArrayAdapter mAdapter;

...

mAdapter = new ArrayAdapter(act, R.layout.list_item, mList);
mListView.setAdapter(mAdapter);

//register item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //do something
        }
    });

//now just add some random String to mList and
mAdapter.notifyDataSetChanged();

//to manually select an item
mListView.setItemChecked(mHistoryList.size() - 1, true);

//to find out which item is currently checked
mListView.getCheckedItemPosition();
<!--Listview xml-->
<ListView
        android:id="@+id/history_view_listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="parent"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:choiceMode="singleChoice"/>

<!--list_item xml-->
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:padding="16dp"
          android:textColor="@color/white_tint_1"
          android:textSize="16sp"
          android:background="@drawable/list_item_selector">
</TextView>

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

    <item android:state_activated="true"
          android:drawable="@color/activity_edit_color_widget_active_30"/>

    <item android:drawable="@color/transparent" />
</selector>