在Android中使用ViewStub作为通用布局

时间:2016-04-06 08:01:09

标签: android android-layout android-fragments

正如我在标题中提到的,我想将ViewStub用作通用布局。我的意思是,目前我有我的基本活动类和基础片段类,可以扩展到其他活动或片段。因为我有泛型类,我想知道我是否可以有一个通用的布局。可能吗?

示例布局:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activities.Activity_Main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/toolbar" />

        <ViewStub
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/viewStub"
            />

    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

@+id/viewStub内容将根据所需的布局发生变化。

1 个答案:

答案 0 :(得分:1)

是的,您可以使用传递所需布局ID的setLayoutResource()方法以编程方式执行此操作。

ViewStub stub = (ViewStub) findViewById(R.id.viewStub);
stub.setLayoutResource(R.layout.some_layout);
View inflatedLayout = stub.inflate();
  

当调用inflate()时,ViewStub将被膨胀的View替换,并返回膨胀的View。这使应用程序可以获得对膨胀的View的引用,而无需执行额外的findViewById()。

这是reference