ListView with Custom Layout for Rows

This tutorial demonstrates how to define custom layout for rows of a list. In this example each row of the list will display text in a text view and
an icon image.

Android listview with custom layout


The steps for creating the applicaion are:

Create the Android Project. Select File>New>Android Project in the Eclipse menu.

Create a class that extends the ListActivity.

public class MainActivity extends ListActivity { }

Create row_layout.xml in the res/layout folder. This will be used as resource layout for rows of list.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/icon_image"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dip"
        android:layout_marginLeft="4dip"
  android:paddingRight="4dip"
        android:src="@drawable/icon"/>
    <TextView
        android:id="@+id/text1"
        android:layout_toLeftOf="@id/icon_image"
        android:layout_alignParentLeft="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
  android:textSize="25sp"
         />
</RelativeLayout>

Open the MainActivity.java and create an array of Strings

private String[] colors = {"Red","Blue","Green","Black","White"};

In the onCreate method, create an ArrayAdapter.

The constructor takes four parameters.

1. Current context
2. Resource id for layout file. In this case tell the ArrayAdapter that you want ot use your custom layout "row_layout", defined in above lines.
3. The TextView id within the layout resource to be populated
4. Reference to the array of Strings.

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.row_layout,R.id.text1,colors);

Set the List Adapter

setListAdapter(adapter);

Final code for the MainActivity.java:

public class MainActivity extends ListActivity {

 private String[] colors = {"Red","Blue","Green","Black","White"};

 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this,R.layout.row_layout,R.id.text1,colors);

        setListAdapter(adapter);
       
    }
}

Conclusion:

In this example you learn how to construct custom layout for rows of the list.

Comments

Didn't know the forum rules alolewd such brilliant posts.

I want to send you an award for most hlefupl internet writer.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.