Add and remove a TextView dynamically in Android

Born Again picture Born Again · Jul 9, 2013 · Viewed 22.4k times · Source

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.

Answer

Tushar Pandey picture Tushar Pandey · Jul 9, 2013
    txtview.setVisibility(View.GONE) ;
    txtview.setVisibility(View.VISIBLE) ;