我想知道实现这一目标的最佳实践是什么。

我希望采用具有相似结构的layout file,因此我可以在整个应用程序的不同活动中使用它。

所以像这样:activity_base.xml

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

    <include
        layout="@layout/content_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>


有什么方法可以在每个活动中以编程方式将layout file注入此include吗?

因此,如果每个活动content_settings.xml都有一个内容文件,则在onCreate或可能的setContentView内将<include />替换为content_home.xml资源文件。

最佳答案

您不能使用include标记来执行此操作,而是使用ViewStub


  ViewStub是一个不可见的,零尺寸的视图,可用于在运行时延迟布局资源的膨胀。使ViewStub可见或调用inflate()时,布局资源会膨胀。然后,ViewStub在其父级中将自己替换为一个或多个膨胀的View。因此,在调用setVisibility(int)inflate()之前,ViewStub存在于视图层次结构中。使用ViewStub的布局参数将膨胀后的视图添加到ViewStub的父级。同样,您可以使用ViewStub的inflatedId属性来定义/覆盖膨胀View的ID。


在您的方案中,您将在膨胀setLayoutResource(int)之前使用ViewStub

关于android - Android Activity ,与模板相同的布局会注入(inject)不同的内容布局,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40321075/

10-08 23:48