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

时间:2013-01-07 11:27:55

标签: 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>

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

3 个答案:

答案 0 :(得分:38)

当你想要展示它时:

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

然后当你想删除它时:

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

相关问题