防止在Android布局中重复代码

时间:2017-07-11 13:28:16

标签: android android-layout android-xml

无论如何都要防止在android layout xml中重复代码? 例如,我有一个TabLayout布局,我想在中显示Tablayout 从右到左的方向所以我使用android:layoutDirection =" rtl" 但是正如你所知,API 17不支持这一点,所以我必须覆盖我的API代码。但是每次我想修改我的布局时,我必须在两个xml文件中重复相同的操作是否有任何简单和更好的方法? / p>

API 17的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/main_background_color">


<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <android.support.design.widget.TabLayout
        android:id="@+id/promotion_type_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabGravity="center"
        app:tabTextAppearance="@style/AppTabTextAppearance"
        app:tabIndicatorColor="@color/cardview_light_background"
        app:tabTextColor="#FFF"
        android:layoutDirection="rtl"


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

    <android.support.v4.view.ViewPager
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/promotion_view_pager"
    android:background="@color/main_background_color" />

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

和API 17下的布局:

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.design.widget.CoordinatorLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/main_background_color">


   <android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <android.support.design.widget.TabLayout
        android:id="@+id/promotion_type_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabGravity="center"
        app:tabTextAppearance="@style/AppTabTextAppearance"
        app:tabIndicatorColor="@color/cardview_light_background"
        app:tabTextColor="#FFF"


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

   <android.support.v4.view.ViewPager
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/promotion_view_pager"
    android:background="@color/main_background_color" />

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

1 个答案:

答案 0 :(得分:0)

您可以在自己的文件中导出布局,并在<include/>布局中Activity/Fragment导出布局,例如

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

请参阅开发者指南Re-using Layouts with include