Skip to main content

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

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout 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:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…