繁体   English   中英

在所有活动中显示自定义视图

[英]Show custom view in all activities

我想展示在所有活动中都应显示的视图。 我不知道如何在android中继承视图。 我所做的是在下面,它显示了第一次活动中的视图,但未显示所有活动中的视图。 此代码是我的BaseActivity的形式,请帮助

LayoutInflater inflater = getLayoutInflater();
View child = inflater.inflate(R.layout.custom_error, null);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT );
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);

addContentView(child, params);

您可以在Activity获得特定于Android的View 例如,下面的以下代码会将TextView添加到Activity的内容区域。

TextView tvSample = new TextView(this);
    tvSample.setText("Hello!");
    ((ViewGroup) hostActivity.findViewById(android.R.id.content)).addView(this);

其中hostActivity是您当前的Activityandroid.R.id.content是特定元素(内容区域,不包括ActionBar )。

或者,如前所述,在布局XML中使用<merge><include>标签。

您可以通过编程的两种解决方案来实现此目的:1)在将子视图添加到父视图之后,需要调用setContentView(parentView)并将父布局传递给它。 并且使用XMl 2)您可以使用include标记。 点击此链接将为您提供帮助。 http://developer.android.com/training/improving-layouts/reusing-layouts.html

您是否尝试过xml的“ include”标签? 它将完成工作。

 <include
 android:id="@+id/container_header_lyt"  
 android:layout_height="wrap_content"
 android:layout_width="fill_parent"
 android:layout_above=...
 android:layout_toLeftOf=...
 layout="@layout/header_logo_lyt" //Name of the xml layout file you want to include
 />

在layout / xxxx中,使用应该重复的布局文件的名称。

与其他任何小部件一样,在您的xml文件中使用上述代码之后。

当您想显示它时:

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文件中给RelativeLayout一个ID来删除View ,然后通过以下rootLayout.removeView(findViewById(R.id.the_id_of_the_relative_layout));删除: rootLayout.removeView(findViewById(R.id.the_id_of_the_relative_layout));

nmw的 回答

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM