Tuesday, October 20, 2009

ListActivity with @android:id/list and empty

Normally, ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list".

In some case if the list is empty, the screen will become nothing. If you want to prompt the user if the list is empty, @android:id/list and @android:id/empty can be used.



Create a new AndroidEmptyListActivity extends ListActivity.
package com.exercise.AndroidEmptyListActivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AndroidEmptyListActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
SetupListView();
}

private void SetupListView()
{

String[] listItems = new String[] {
"Hello!",
"It's a Demo to use ListActivity,",
"with list/empty...",
"Is it Great?",
"android-er.blogspot.com"
};

/*
String[] listItems = new String[] {
};
*/

ArrayAdapter<String> listItemAdapter
= new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
listItems);

ListView lv = (ListView)this.findViewById(android.R.id.list);
lv.setAdapter(listItemAdapter);
}
}


Modify the main.xml to have a ListView with android:id="@android:id/list", and a TextView android:id="@android:id/empty".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:id="@android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List is Empty"/>
</LinearLayout>


If the List is not empty, the ListView will be shown, otherwise TextView will be shown.

Download the files.

No comments:

Post a Comment