如何在没有片段的活动之间共享公共布局

use*_*231 12 layout android android-activity

有没有可能的方法在活动之间共享布局(部分)?例如,在我的应用程序中,所有活动都有类似的布局,顶部是长操作指示器(进度条,在没有执行任何操作时隐藏),底部用于显示错误.所有活动只有中间部分不同.见下图.

在此输入图像描述

所以我的问题是,是否有可能为我的应用程序中的所有活动重用公共布局(加载和错误部分)?(目前我不想因为某些原因使用片段来做)

也许布局资源应该是这样的:

layoutfolder

activity_common.xml

activity_one_content.xml

activity_two_content.xml
Run Code Online (Sandbox Code Playgroud)

谢谢

Jon*_*Fry 16

您可以创建一个抽象的"基础"活动,您可以从中扩展所有活动,覆盖setContentView以合并基础和子活动布局.

这样,您就可以处理基本活动中的所有加载/错误代码,只需在隐藏和显示子活动中的视图之间切换.

抽象活动:

public abstract class BaseActivity extends Activity {

    protected RelativeLayout fullLayout;
    protected FrameLayout subActivityContent;

    @Override
    public void setContentView(int layoutResID) {
        fullLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_base, null);  // The base layout
        subActivityContent = (FrameLayout) fullLayout.findViewById(R.id.content_frame);            // The frame layout where the activity content is placed.
        getLayoutInflater().inflate(layoutResID, subActivityContent, true);            // Places the activity layout inside the activity content frame.
        super.setContentView(fullLayout);                                                       // Sets the content view as the merged layouts.
    }

}
Run Code Online (Sandbox Code Playgroud)

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/loading_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/error_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

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


MrH*_*rio 5

您可以使用includein XMLto .. 包含布局代码的可重用部分。

例如,这是我Toolbar在我的应用程序中使用的布局文件:

// /res/layout/component_toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:taggr="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/primary"
    android:minHeight="?attr/actionBarSize"
    taggr:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    taggr:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
Run Code Online (Sandbox Code Playgroud)

现在,假设我想Toolbar在不同的中再次使用它Activity,这就是我必须写的全部内容:

// /res/layout/whatever_layout_this_might_be.xml

<include layout="@layout/component_toolbar" />
Run Code Online (Sandbox Code Playgroud)

请记住,这只会复制布局- 而不是所述小部件/组件的实际行为。

如果您想真正复制所有方面(布局、行为),恐怕Fragment是唯一的出路。