Get value of selected item in listview in android

Get listview clicked item on android.

Application builder can get selected list item value through setOnItemClickListener() function. By selecting list array element developer can perform various task on it like open a new list view or any target page. So here is the complete step by step tutorial for Get value of selected item in listview in android.

What i am doing in this project : I am creating string array and set that array items into listview after that setting up setOnItemClickListener() function on listview and Print toast message with list selected element.

android-project-download-code-button

Get value of selected item in listview in android .

Code for MainActivity.java file.

 package com.example.listviewselecteditem;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

 ListView listView;
 
 // Define string array.
 String[] listValue = new String[] {"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 listView = (ListView)findViewById(R.id.listView1);
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2, android.R.id.text1, listValue);
 
 listView.setAdapter(adapter); 
 
 // ListView on item selected listener.
 listView.setOnItemClickListener(new OnItemClickListener()
 {

 @Override
 public void onItemClick(AdapterView<?> parent, View view,
 int position, long id) {
 // TODO Auto-generated method stub
 Toast.makeText(MainActivity.this, listValue[position], Toast.LENGTH_SHORT).show();
 }
 });
 
 }

 
}

Code for activity_main.xml layout file.

<RelativeLayout 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"
 tools:context="com.example.listviewselecteditem.MainActivity" >

 <ListView
 android:id="@+id/listView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true" >
 </ListView>

</RelativeLayout>

Screenshot:

Get value of selected item in listview in android

Click Here To Download Get value of selected item in listview in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *