Monday, April 6, 2015

How to use ListView in Android

1. Android ListView Example

activity_main.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:padding="16dp"
    tools:context=".MainActivity"
    >
    <ListView
        android:id="@+id/lv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        />
</RelativeLayout>
MainActivity.java (Partial code)

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

 //Initialize a new String Array
 /*
  Those are the only color names that android parseColor(String colorString)
   method support. Parameter's other supported the formats are
   #RRGGBB #AARRGGBB
  */
 final String[] colorsArray = new String[]{
   "red", "blue", "green", "black", "white",
   "gray", "cyan", "magenta", "yellow", "lightgray",
   "darkgray", "grey", "lightgrey", "darkgrey", "aqua",
   "fuchsia", "lime", "maroon", "navy", "olive",
   "purple", "silver", "teal"
 };

 //Get widgets reference from XML layout
 final ListView lView = (ListView) findViewById(R.id.lv);

 //Initialize an ArrayAdapter and data bind with a String Array
 ArrayAdapter<String> adapter = new ArrayAdapter<String>
   (this,android.R.layout.simple_list_item_1,colorsArray);

 //Data bind ListView with ArrayAdapter
 lView.setAdapter(adapter);

 //Set an Item Click Listener for ListView items
 lView.setOnItemClickListener(new OnItemClickListener(){
  //onItemClick() callback method
  public void onItemClick(AdapterView<?> parent, View v, int position, long id){
   //Get ListView clicked item's corresponded Array element value
   String clickedItemValue = Arrays.asList(colorsArray).get(position);

   //Generate a Toast message
   String toastMessage = "Position : "+position + " || Value : " + clickedItemValue;

   //Apply the ListView background color as user selected item value
   lView.setBackgroundColor(Color.parseColor(clickedItemValue));

   //Display user response as a Toast message
   Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT).show();
  }
 });
}
Additional imported classes

import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Arrays;
import android.graphics.Color;

2. ListView Simple Divider

activity_main.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:padding="16dp"
    tools:context=".MainActivity"
    >
    <ListView
        android:id="@+id/lv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:cacheColorHint="#00000000"
        android:divider="#00BFFF"
        android:dividerHeight="2dp"
        />
</RelativeLayout>

3. ListView Drawable Gradient Divider

activity_main.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:padding="16dp"
    tools:context=".MainActivity"
    >
    <ListView
        android:id="@+id/lv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:divider="@drawable/listview_divider"
        android:dividerHeight="3dp"
        />
</RelativeLayout>
res/drawable/listview_divider.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:type="linear"
                android:startColor="#ffe7cb"
                android:endColor="#ffe7cb"
                android:centerColor="#FF8C00"
                android:angle="0"
                android:gradientRadius="90"
                />
        </shape>
    </item>
</selector>

4. ListView Header and Footer

activity_main.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:padding="16dp"
    tools:context=".MainActivity"
    >
    <ListView
        android:id="@+id/lv"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        />
</RelativeLayout>
MainActivity.java (Partial code)

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

 //Initialize a new String Array
 String[] colorsArray = new String[]{
   "OldLace","Olive","OliveDrab","Orange",
   "OrangeRed","Orchid"
 };

 //Get widgets reference from XML layout
 final ListView lView = (ListView) findViewById(R.id.lv);

 //Initialize an ArrayAdapter and data bind with a String Array
 ArrayAdapter<String> adapter = new ArrayAdapter<String>
   (this,android.R.layout.simple_list_item_1,colorsArray);

 //Data bind ListView with ArrayAdapter
 lView.setAdapter(adapter);

 //.........Creating a Header for ListView..........
 //Initialize a new TextView instance
 TextView tv = new TextView(this);

 //Set a text for TextView widget
 tv.setText("ListView Header");

 //Apply TextView text color to MediumSlateBlue
 tv.setTextColor(Color.parseColor("#7B68EE"));

 //Apply TextView background color to LightSteelBlue
 tv.setBackgroundColor(Color.parseColor("#B0C4DE"));

 tv.setPadding(15,15,15,15);

 //Set the TextView as ListView Header and it is non selectable
 lView.addHeaderView(tv,"",false);

 //.........Creating a Footer for ListView..........
 //Initialize a new TextView widget
 TextView footerTV = new TextView(this);

 //Set the footer text to display
 footerTV.setText("...*End of list*...");

 //Apply the text align to horizontal center
 footerTV.setGravity(Gravity.CENTER_HORIZONTAL);

 //Set textView text color to Gainsboro
 footerTV.setBackgroundColor(Color.parseColor("#DCDCDC"));

 //Attach the TextView as ListView footer
 lView.addFooterView(footerTV,"",false);
}
Additional imported classes

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.graphics.Color;
import android.widget.TextView;
import android.view.Gravity;
More android examples