ArhamTechMind

Listview Example


ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.


For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.


list.xml

<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" 
    android:paddingLeft="@dimen/activity_horizontal_margin"    
    android:paddingRight="@dimen/activity_horizontal_margin"    
    android:paddingTop="@dimen/activity_vertical_margin"    
    android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.blogspot.help2computer.test.List">

<ListView  
      android:layout_width="wrap_content"        
      android:layout_height="wrap_content"        
      android:id="@+id/listView"        
      android:layout_alignParentTop="true"        
      android:layout_alignParentLeft="true"        
      android:layout_alignParentStart="true"        
      android:layout_marginTop="68dp" />
</RelativeLayout>

List.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class List extends AppCompatActivity {

ListView listView;

@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);

listView = (ListView) findViewById(R.id.listView);

// Defined Array values to show in ListView  

        String[] values = new String[]{"Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View" };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);

listView.setAdapter(adapter) ;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index  
              int itemPosition     = position;
                   // ListView Clicked item value      
             String  itemValue    = (String) listView.getItemAtPosition(position);
// Show Alert  
           Toast.makeText(getApplicationContext(),itemValue , Toast.LENGTH_LONG)
.show();
}
});


}
}

Leave a Comment

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