Android的onLayout、layout方法讲解
来源:互联网 发布:super this区别java 编辑:程序博客网 时间:2024/06/12 05:17
onLayout方法是ViewGroup中子View的布局方法,用于放置子View的位置。放置子View很简单,只需在重写onLayout方法,然后获取子View的实例,调用子View的layout方法实现布局。在实际开发中,一般要配合onMeasure测量方法一起使用。
onLayout方法:
1
2
3
@Override
protected
abstract
void
onLayout(
boolean
changed,
int
l,
int
t,
int
r,
int
b);
layout方法:
1
public
void
layout(
int
l,
int
t,
int
r,
int
b);
平常开发所用到RelativeLayout、LinearLayout、FrameLayout...这些都是继承ViewGroup的布局。这些布局的实现都是通过都实现ViewGroup的onLayout方法,只是实现方法不一样而已。
下面是一个自定义ViewGroup的Demo,用onLayout和layout实现子View的水平放置,间隔是20px
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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布局:
1
2
3
4
5
6
7
8
9
10
<relativelayout xmlns:android=
"https://schemas.android.com/apk/res/android"
xmlns:tools=
"https://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>
效果如图所示:
上图MyViewGroup是蓝色,两个子View分别为红色和绿色。
在自定义View中,onLayout配合onMeasure方法一起使用,可以实现自定义View的复杂布局。自定义View首先调用onMeasure进行测量,然后调用onLayout方法,动态获取子View和子View的测量大小,然后进行layout布局。
阅读全文
0 0
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- Android的onLayout、layout方法讲解
- android onLayout、layout方法学习
- ViewGroup的onLayout、layout方法
- Android-UI布局---onLayout、layout方法
- Android onLayout、layout区别
- 条款17:以独立的语句将newed对象置入智能指针
- 【正一专栏】为何我们要侥幸而又苟且地活着
- $.ajax()方法详解
- Android Palette 调色板 的使用
- 如何基于OSS和MTS,快速搭建音视频文件上传服务?
- Android的onLayout、layout方法讲解
- 关于嵌套类与外围类的详细解释
- mt6735[Call] USSD是否支持USSD Phase 1 & 2 2
- Spring boot + Maven环境搭建comet4j前端页面推送
- c#导入导出Excel
- vipkid创始人米雯娟传奇:高二退学,创业逆袭成50亿教育巨头
- 17.Python
- 乐变热更新后台的使用
- Docker1.12.1之swarm集群搭建与使用