I'm pulling my hair out trying to figure this out. From all the tutorials I've read, the way I have this setup should work. I have a ListActivity that is using a custom adapter to display some data. I'd like to display a "no items found" message if the adapter is empty.
This is my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/BaseStyle"
android:orientation="vertical"
android:padding="5dip"
>
<ListView android:id="@android:id/list"
style="@style/BaseStyle"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/empty"
style="@style/BaseStyle.Title"
android:text="No Items Found"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
style="@style/BaseStyle.Title"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
This is my code:
public class Main extends ListActivity {
private CustomAdapter adapter;
private String[] items = {};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter = new CustomAdapter();
PopulateItems();
for (String item : items)
adapter.addItem(item);
this.setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
private class CustomAdapter extends BaseAdapter {
private String[] mData;
private LayoutInflater mInflater;
public CustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(String item) {
mData.add(item);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
String item = (String)this.getItem(position);
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.main, parent, false);
holder.text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
TextView tvText = holder.text;
tvText.setText(item);
}
static class ViewHolder {
TextView text;
}
What happens is the "No Items Found" text displays fine, when the "items" string array has no data. There is a process in the PopulateItem() method that will populate the array with data, and if there is data, the "No Items Found" text can still be seen on each row of the listing, "underneath" the data. So the empty text is basically being overlaid by the data.