【问题标题】:How to remove a view added using addContentView?如何删除使用 addContentView 添加的视图?
【发布时间】:2015-04-29 21:08:47
【问题描述】:

我已使用 addContentView() 成功地将子视图添加到父视图。但是当我试图删除视图时,它给了我一个空指针异常。

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

【问题讨论】:

  • 你能发布一个堆栈跟踪吗?您从哪里获得 NPE?

标签: java android


【解决方案1】:

在 xml 中给你的根布局一个 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>

在代码中你可以做这样的事情

View viewToRemove= findViewById(R.id.InflateViewLinearLayout);
if (viewToRemove != null && (ViewGroup) viewToRemove.getParent() != null && viewToRemove instanceof ViewGroup)
      ((ViewGroup) viewToRemove.getParent()).removeView(viewToRemove);

【讨论】:

  • 谢谢!!这对我有帮助。但是你能告诉我为什么我应该为布局声明一个 id 吗?是否有必要使用R.id.id_of_layout 而不是R.layout.id_of_layout
  • 您可以使用 findViewById 按 ID 或使用 view.findViewWithTag(tag) 按标签查找视图。因此,您将需要 ID 或标签。你只需要 R.layout... 来膨胀一个布局,因为它会返回整个布局而不仅仅是一个 id。 R 将帮助您从资源中获得所需。看这里:stackoverflow.com/questions/6434970/…
【解决方案2】:
  ViewGroup viewHolder = (ViewGroup)ViewToRemove.getParent();
  viewHolder.removeView(ViewToRemove);

这对我有用。

【讨论】:

    【解决方案3】:

    @Aalia 您必须通过 id 和布局来识别视图。

    View myView = findViewById(R.id.id_of_the_customlayout);
    

    请设置该 customlayout.xml 的顶部 ViewGroup 的 id。

    【讨论】:

    • public static final 类布局 { public static final int activity_main=0x7f030000;公共静态最终 int customlayout=0x7f030001; }
    • customlayout 的 ID 位于布局类,而不是 id 类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2011-10-10
    • 2020-08-23
    相关资源
    最近更新 更多