Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove a TextView dynamically in Android

I have set up a FrameLayout which has a TextView on top of a ListView. Now, in the MainActivity, after executing some code, I check whether the ListView is empty. If it is, I display the TextView, if not, I remove the TextView.

The code is as follows:

Following is the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvAddItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Add some subjects"
        android:textSize="20sp" />

    <ListView
        android:id="@+id/ItemsList"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

</FrameLayout>

In the MainActivity class, I do the following:

MainActivity.java

TextView tvNoItem = (TextView) findViewById(R.id.tvAddItem);
ListView subListView = (ListView) findViewById(R.id.itemsList);
FrameLayout fl = (FrameLayout) findViewById(R.id.flMain);

ArrayList<Item> itemsList;

//some code

if(itemsList.isEmpty()) {
    fl.addView(tvNoItem);
} else {
    fl.removeView(tvNoItem);
}

Now, when I run it and I add some items to the list, the TextView (tvNoItem) is removed indeed. But all I see is a blank list - the list items are not visible. [BTW, the list is working fine. When I remove the TextView from main.xml, I can see all the list items.] Please help.

like image 448
Born Again Avatar asked Jul 09 '13 06:07

Born Again


2 Answers

    txtview.setVisibility(View.GONE) ;
    txtview.setVisibility(View.VISIBLE) ;
like image 84
Tushar Pandey Avatar answered Oct 29 '22 17:10

Tushar Pandey


Why don't you use ListView's emptyView option.

Here is a nice post about showing empty view while your adapter is empty. It'll be automatically shown when your Adapter's source is empty.

Android – ListView => setEmptyView()

You don't need to check whether you data source (ArrayList) is empty, android framework will handle all the hiding and showing implementation.

Make sure to call setEmptyView() before you call setAdapter() on the ListView.

like image 20
Adil Soomro Avatar answered Oct 29 '22 18:10

Adil Soomro