[转]技巧和设计模式 --- 视图和布局

本文介绍如何通过简化视图层级和采用高效布局策略来提升Android应用的用户界面性能,包括使用TextView复合图片、ViewStub懒加载、merge标签合并视图、RelativeLayout简化布局、自定义视图及布局等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.越简单越好

 

 

如果一个窗口包含很多视图

 

[1] 启动动时间长

 

[2] 测量时间长

 

[3] 布局时间长

 

[4] 绘制时间长

 

 

如果视图树深度太深

 

[1] StackOverflowException

 

[2] 用户界面反应速度很慢

 

2.解决的办法

 

 

[1] 使用TextView的复合drawables减少层次

 

 

[2] 使用ViewStub延迟展开视图

 

[3] 使用<merge>合并中间视图

 

[4] 使用RelativeLayout减少层次

 

[5] 使用自定义视图

 

[6] 使用自定义布局

 

关于[1]

 



替代为

 


 

关于[2] 使用ViewStub延迟展开视图

 


首先在XML布局文件中定义 ViewStub

 

 

<ViewStub android:id = "@+id/stub_import"
android:inflatedId="@+id/panel_import"
android:layout="@layout/progress_overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>

 

 

在需要展开视图时

 

 

findViewById(R.id.stub_import).setVisibility(View.VISIBLE);
// 或者
View importPanel = ((ViewStub)
findViewById(R.id.stub_import)).inflate();
 

 

展开之后变成

 


 

关于[3]使用<merge>合并视图:略

 

关于[4]使用RelativeLayout减少层次,总得意思就是用RelativeLayout解决复杂的布局,比如代替LinearLayout复杂的布局

 

关于[5]自定义视图

 

 

class CustomView extends View {
    @Override
    protected void onDraw(Canvas canvas) {
        // 加入你的绘图编码
   }
    @Override
    protected void onMeasure(int widthMeasureSpec,
    int heightMeasureSpec) {
        // 计算视图的尺寸
        setMeasuredDimension(widthSpecSize, heightSpecSize);
    }
}

 

 

关于[6]自定义布局

 

 

class GridLayout extends ViewGroup {
    @Override
    protected void onLayout(boolean changed, int l, int t,
    int r, int b) {
        final int count = getChildCount();
        for (int i=0; i < count; i++) {
            final View child = getChildAt(i);
           if (child.getVisibility() != GONE) {
           // 计算子视图的位置
          child.layout(left, top, right, bottom);
          }
        }
     }
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值