Saturday 20 December 2014

Highlight Selected Items in ListView


Hello Friends'

In this post i will show how to highlight selected items in ListView.


For this took two layout.

Main layout containing ListView. 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
<--choiceMode is multipleChoice-->
        android:choiceMode="multipleChoice" >
    </ListView>

</LinearLayout>

This layout is used for each row of ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
<--This attribute will highlight the row-->
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:text="TextView" />

</LinearLayout>


MainActivity java file code is:

package in.blogspot.longjamcode;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting String array fron res folder
String[] array = getResources().getStringArray(R.array.city_array);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_row_layout, R.id.textView1, array);
listView.setAdapter(adapter);
}
}

The Output is:

For full source code click here

No comments:

Post a Comment