How to remove a view in your xml layout file using program?

By | September 28, 2011

Hello everyone,
this is a simple example showing how to remove a view in android that is created using your xml file.

This is the xml file that contains a TextView

<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="CoderzHeaven"
    android:id="@+id/tv"
    />
</LinearLayout>

Here is the java code for removing this view

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class RemoveViewDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        View tv= (View)findViewById(R.id.tv);
        ((LinearLayout)tv.getParent()).removeView(tv);
    }
}

After running this program you will not see the TextView that was in your layout file.
Please leave your valuable comments on this post.

Leave a Reply

Your email address will not be published. Required fields are marked *