Reputation: 35
I have successfully added a child view to a parent view using addContentView(). But when I am trying to remove the view it is giving me a Null Pointer Exception.
//Working Code
Button button1=(Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
getWindow().addContentView(getLayoutInflater().inflate(R.layout.customlayout, null),new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT ));
}
});
//Code not Working
Button button2=(Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
View myView = findViewById(R.layout.customlayout);
ViewGroup parent = (ViewGroup) myView.getParent();
parent.removeView(myView);
}
});
Upvotes: 2
Views: 2150
Reputation:
ViewGroup viewHolder = (ViewGroup)ViewToRemove.getParent();
viewHolder.removeView(ViewToRemove);
This is what is working for me.
Upvotes: 1
Reputation: 498
in xml give your root layout an id
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/InflateViewLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
and in code you can do something like this
View viewToRemove= findViewById(R.id.InflateViewLinearLayout);
if (viewToRemove != null && (ViewGroup) viewToRemove.getParent() != null && viewToRemove instanceof ViewGroup)
((ViewGroup) viewToRemove.getParent()).removeView(viewToRemove);
Upvotes: 1
Reputation: 12478
@Aalia You must identify the view with its id but layout.
View myView = findViewById(R.id.id_of_the_customlayout);
Please set an id of the top ViewGroup of that customlayout.xml.
Upvotes: 0