Android:addview() - 在活动之上添加新视图

tee*_*kib 7 android android-layout android-activity

我有以下布局与imageview和textfield,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="26dp"
        android:layout_marginTop="22dp"
        android:src="@drawable/a01" />

     <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="31dp"
        />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

这个布局是透明的,我想在特定活动的基础上调用此布局,当特定活动首次启动时,如何实现它addview()

nmw*_*nmw 39

当你想要展示它时:

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
View.inflate(this, R.layout.overlay_layout, rootLayout);
Run Code Online (Sandbox Code Playgroud)

然后当你想删除它:

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
rootLayout.removeViewAt(rootLayout.getChildCount()-1);
Run Code Online (Sandbox Code Playgroud)

这是一个简洁的解决方案,您应该删除View通过给RelativeLayoutXML文件中的ID,然后取出用:rootLayout.removeView(findViewById(R.id.the_id_of_the_relative_layout));.