Tuesday, June 30, 2015

Android ListView Example

Here's a very simple example to get you started with an Android ListView. This example just displays a hard-coded list of colors in a ListView control. The key components are the ArrayAdapter and the additional layout file.

ListViews work via an adapter pattern. So, we have to create an adapter that lists the items that we're going to display in the ListView. We also have to create a layout with the type of entity that we're displaying for each item in the ListView. In this example, each item in the ListView will be a simple TextView. However, it could be something more involved (like an image).


res/layout/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"

    tools:context="${relativePackage}.${activityClass}" >



    <ListView

       android:id="@+id/list_of_colors"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent"

       android:padding="10dp"

       android:textSize="20sp" />


</RelativeLayout>


res/layout/listview_item.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
 <TextView android:id="@+id/color_item"   
   android:layout_width="fill_parent"   
   android:layout_height="wrap_content"  
   android:padding="10dp"  
   android:textSize="16sp" />
 
</LinearLayout>


src/{package-name}/MainActivity.java :

public class MainActivity extends Activity {
 
    private  final String[] COLORS = new String[] { "Red", "Orange", 
             "Yellow", "Green", "Blue", "Indigo", "Violet" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
  
       ArrayAdapter adapter = new ArrayAdapter(this, R.layout.listview_item,
                        R.id.color_item, COLORS);
  
       ListView lv = (ListView) findViewById(R.id.list_of_colors);
       lv.setAdapter(adapter);
    }
}

I put this code on GitHub for you to reference: https://github.com/travisdazell/android-listview-example

No comments:

Post a Comment