Friday, March 23, 2012

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


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

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
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
<?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
?
Drag and copy the code
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
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.

No comments: