Android:addview()-在活动顶部添加新视图

Android: addview()- adding a new view on top of activity

我有一个带有imageview和textfield的以下布局,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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>

此布局将是透明的,我想在特定活动之上调用此布局,当特定活动首次开始时,如何使用addview()来实现?


当您想显示它时:

1
2
FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
View.inflate(this, R.layout.overlay_layout, rootLayout);

然后,当您要删除它时:

1
2
FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
rootLayout.removeViewAt(rootLayout.getChildCount()-1);

这是一个简洁的解决方案,您应该通过在XML文件中给RelativeLayout一个ID来删除View,然后通过以下方式删除:rootLayout.removeView(findViewById(R.id.the_id_of_the_relative_layout));


请使用以下代码添加视图。

1
2
3
4
5
6
7
8
9
10
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);

// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");

// insert into main view
View insertPoint =(View) findViewById(R.id.insert_point); // edited.
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));


呼叫活动的布局应位于FrameLayout内部(因为在此布局中,最后添加的视图将始终位于上一个视图的顶部),
在调用活动的onCreate方法中,使用LayoutInflater膨胀给定的布局,并直接使用活动的addView方法。