2

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);
        }   
    });

3 Answers3

1

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);
momor10
  • 478
  • 3
  • 11
  • Thanks!! This helped me. But can you tell me why I should declare an id for layout? is it necessary to use `R.id.id_of_layout` instead of `R.layout.id_of_layout` ? – Aalia Jindal Jan 13 '15 at 14:58
  • You can look for a View either by ID using findViewById or by Tag using view.findViewWithTag(tag). So you will need the ID or a Tag. you will only need R.layout... for inflating a layout, because it will return the whole layout and not just an id. R will help you to get what you need from your resources. look here: http://stackoverflow.com/questions/6434970/difference-between-r-layout-and-android-r-layout – momor10 Jan 13 '15 at 15:01
1
  ViewGroup viewHolder = (ViewGroup)ViewToRemove.getParent();
  viewHolder.removeView(ViewToRemove);

This is what is working for me.

0

@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.

hata
  • 11,633
  • 6
  • 46
  • 69