Android抽象布局的使用

5 篇文章 0 订阅

1. 重用布局

当我们在开发过程中,有几个布局界面存在较多的共同模块,可以进行代码块的重用,编写进入一个共同的布局界面,然后在布局文件中使用include标签进行引入。

2. 减少布局层数

当开发过程中,经常会嵌套很多布局,导致布局层级很深。所以当我们明确父View和子View的布局相同时,完全可以使用merge来减少布局深度。

 <?xml version="1.0" encoding="utf-8"?>
 <merge
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     >
    <include layout="@layout/inclute_title_bar"/>
 </merge>

3. 延迟加载视图

viewStub是一个宽高为0的不可见View,只有通过serVisisbility和inflate才会加载目标布局,从而达到延迟加载视图的目的。

//ViewStub例子
 <ViewStub
       android:inflatedId="@+id/network_error_id"
       android:layout="@layout/network_error"
       android:id="@+id/network_error"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>

和GONE不同,设置View为GONE,在渲染时还是会加载到视图树中。ViewStub只有在inflate后才会加载到视图树中(注意控制,ViewStub只能inflate一次),减少视图渲染的压力。

4. FrameLayout 帧布局

设计FrameLayout是为了显示单一Widget,布局会默认把控件放在屏幕的左上角区域,后续添加的控件会覆盖前一个。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <TextView    
        android:layout_width="200dp"    
        android:layout_height="200dp"    
        android:background="#FF0000" />    
    <TextView    
        android:layout_width="150dp"    
        android:layout_height="150dp"    
        android:background="#00FFFF" />    
     <TextView    
        android:layout_width="100dp"    
        android:layout_height="100dp"    
        android:background="#FFFF00" />
 
</FrameLayout>

5. 百分比布局PercentFrameLayout

百分比布局中,我们不在使用wrap_content和match_parent指定大小,而是用百分比指定控件在布局中的大小,这样的或就可以按任意比例切割布局。(Android团队将百分比布局定义在了support中)

dependencies {
    compile 'com.android.support:percent:24.2.1'
}
<android.support.percent.PercentFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:id="@+id/button1"
        android:text="Button 1"
        android:layout_gravity="left|top"
        app:layout_widthPercent = "%50"
        app:layout_heightPercent = "%50"/>
 
</android.support.percent.PercentFrameLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值