android:layout_with="",Re-using Layouts with <include/> | Android中文API

Although Android offers a variety of widgets to provide small and re-usable interactive elements,

you might also need to re-use larger components that require a special layout. To efficiently

re-use complete layouts, you can use the and tags

to embed another layout inside the current layout.

Reusing layouts is particularly powerful as it allows you create reusable complex layouts. For

example, a yes/no button panel, or custom progress bar with description text.

It also means that any elements of your application that are common across multiple layouts can be

extracted, managed separately, then included in each layout. So while

you can create individual UI components by writing a custom

Create a Re-usable Layout

If you already know the layout that you want to re-use, create a new XML file and define the

layout. For example, here's a layout from the G-Kenya codelab that defines a title bar to be

included in each activity (titlebar.xml):

android:layout_width=”match_parent”

android:layout_height="wrap_content"

android:background="@color/titlebar_bg">

android:layout_height="wrap_content"

android:src="@drawable/gafricalogo" />

The root

Use the Tag

Inside the layout to which you want to add the re-usable component, add the tag. For example, here's a layout from the

G-Kenya codelab that includes the title bar from above:

Here's the layout file:

android:orientation="vertical"

android:layout_width=”match_parent”

android:layout_height=”match_parent”

android:background="@color/app_bg"

android:gravity="center_horizontal">

android:layout_height="wrap_content"

android:text="@string/hello"

android:padding="10dp" />

...

You can also override all the layout parameters (any android:layout_* attributes) of the

included layout's root view by specifying them in the tag. For

example:

android:layout_width=”match_parent”

android:layout_height=”match_parent”

layout=”@layout/title”/>

Use the Tag

The tag helps eliminate redundant view groups in your view hierarchy

when including one layout within another. For example, if your main layout is a vertical

To avoid including such a redundant view group, you can instead use the

element as the root view for the re-usable layout. For example:

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/add"/>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/delete"/>

Now, when you include this layout in another layout (using the tag), the

system ignores the element and places the two buttons directly in the

layout, in place of the tag.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值