In this tutorial we will create a ListView using array , array items will be displayed in listview. We will also handle Item Clicks , I'll display a Toast on each item click , you can do your functionality.
Step 1: Create a new project OR Open your project
Step 2: Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><ListViewandroid:id="@+id/list_view"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
MainActivity.java
package com.blogspot.devofandroid.myapplication;import android.content.DialogInterface;import android.os.Bundle;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MainActivity extends AppCompatActivity {ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.list_view);String[] values = new String[]{"Item 1" , "Item 2" , "Item 3" , "Item 4" , "Item 5" ,};ArrayAdapter<String> adapter = new ArrayAdapter<String>(this ,android.R.layout.simple_list_item_1 , android.R.id.text1 , values);listView.setAdapter(adapter);listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){public void onItemClick(AdapterView<?> parent , View view , int position , long id){if (position == 0) {Toast.makeText(MainActivity.this , "Item One Clicked" , Toast.LENGTH_SHORT).show();}else if (position == 1) {Toast.makeText(MainActivity.this , "Item Two Clicked" , Toast.LENGTH_SHORT).show();}else if (position == 2) {Toast.makeText(MainActivity.this , "Item Three Clicked" , Toast.LENGTH_SHORT).show();}else if (position == 3) {Toast.makeText(MainActivity.this , "Item Four Clicked" , Toast.LENGTH_SHORT).show();}else if (position == 4) {Toast.makeText(MainActivity.this , "Item Five Clicked" , Toast.LENGTH_SHORT).show();}}});}}
0 Response to "Listview Using Array With Item Click Listener"