3

If you look at the Android documentation about how to implement a List View and populate it you will notice that they only teach you how to do it in Java extending ListActivity instead of the normal Activity, but how would the same code (layout and populate the list) using XML layout files and extending Activity?

I'm asking this because I want to implement a RelativeLayout and add more elements to the screen where the ListView is with more flexibility than using .inflate() and addHeaderView()/addFooterView().

Nathan Campos
  • 28,769
  • 59
  • 194
  • 300

2 Answers2

8

I think the way you are looking is creating and populating your own list.

  • create a main layout (mainLayout.xml) // It should have a linear layout at least one.
  • create a template layout for your list rows.
  • In your activity inflate your template in for loop, populate it and append it to your main layout.

here is an example,

listtemplate.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:id="@+id/listLayout"
    android:clickable="true"
    >
            <TextView android:layout_width="wrap_content" 
                      android:textAppearance="?android:attr/textAppearanceLarge" 
                      android:layout_marginLeft="3dp"
                      android:layout_height="wrap_content" 
                      android:layout_alignParentLeft="true"
                      android:layout_alignParentTop ="true"
                      android:id="@+id/mainText" 
                      android:text="TextView">
                </TextView>
</RelativeLayout>

and in your activity,

public void CreateAndAppendListLayout() 
{
   List<String> mainList; //populate it...
   LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
   LayoutInflater li =  (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   for (int i = 0; i < mainList.size();  i++){
       View tempView = li.inflate(R.layout.listtemplate, null);
       TextView textMain = (TextView) tempView.findViewById(R.id.mainText);

       textMain.setText(mainList.get(i)); 
       mainLayout.addView(tempView);
      } 
}
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
1

You can extend from Activity with no problems. Extending from ListActivity just helps you by doing most of the (very easy) legwork. You can see the source code to understand what it does. It boils down to calling findViewById() and setting the adapter. The hardest part about dealing with ListViews are the Adapters, not the ListViews themselves.

dmon
  • 30,048
  • 8
  • 87
  • 96