android onLayout、layout方法学习

[color=red]onLayout方法是ViewGroup中子View的布局方法,用于放置子View的位置。[/color]放置子View很简单,[b]只需在重写onLayout方法[/b],然后获取子View的实例,调用子View的layout方法实现布局。在实际开发中,一般要配合onMeasure测量方法一起使用。


@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);

[b]参数的含义如下图:[/b]

[img]http://dl2.iteye.com/upload/attachment/0114/4468/9fb56189-ee69-3627-b719-fb4a2cdea7bd.jpg[/img]

该方法在ViewGroup中定义是抽象函数,[color=red]继承该类必须实现onLayout方法,而ViewGroup的onMeasure并非必须重写的。[/color]View的放置都是根据一个矩形空间放置的,onLayout传下来的l,t,r,b[color=red]分别是放置父控件的矩形可用空间(除去margin和padding的空间)的左上角的left、top以及右下角right、bottom值。[/color]

layout方法:

public void layout(int l, int t, int r, int b);


该方法是View的放置方法,在View类实现。[color=red]调用该方法需要传入放置View的矩形空间左上角left、top值和右下角right、bottom值。[/color]这四个值是相对于父控件而言的。例如传入的是(10, 10, 100, 100),则该View在距离父控件的左上角位置(10, 10)处显示,显示的大小是宽高是90(参数r,b是相对左上角的),这有点像绝对布局。

平常开发所用到RelativeLayout、LinearLayout、FrameLayout...这些都是继承ViewGroup的布局。[color=red]这些布局的实现都是通过都实现ViewGroup的onLayout方法,只是实现方法不一样而已。[/color]

下面是一个自定义ViewGroup的Demo,用onLayout和layout实现子View的水平放置,间隔是20px


public class MyViewGroup extends ViewGroup {

// 子View的水平间隔
private final static int padding = 20;

public MyViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub

// 动态获取子View实例
for (int i = 0, size = getChildCount(); i < size; i++) {
View view = getChildAt(i);
// 放置子View,宽高都是100
view.layout(l, t, l + 100, t + 100);
l += 100 + padding;
}

}

}


Activity的XML布局:


<relativelayout 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:padding="10dp">

<com.example.layout.myviewgroup android:layout_width="match_parent" android:layout_height="100dp" android:background="#0000ff">

<view android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff0000">
<view android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00ff00">

</view></view></com.example.layout.myviewgroup>

</relativelayout>


效果如图所示:

[img]http://dl2.iteye.com/upload/attachment/0114/4480/2e4a3f9f-cfae-3157-acb9-d4f5829e6d0d.png[/img]


上图MyViewGroup是蓝色,两个子View分别为红色和绿色。

在自定义View中,[color=red]onLayout配合onMeasure方法一起使用,可以实现自定义View的复杂布局。[/color]自定义View首先调用onMeasure进行测量,然后调用onLayout方法,动态获取子View和子View的测量大小,然后进行layout布局。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值