我已使用 addContentView() 成功将 subview 添加到父 View 。但是当我尝试删除 View 时,它给了我一个空指针异常。
//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);
}
});
最佳答案
在 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);
关于java - 如何删除使用 addContentView 添加的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27924668/