您的位置:首页 > 其它

自定义View由浅入深__ViewGroup(一)

2017-01-07 16:37 267 查看
这两天工作不是很忙,把自定义View相关的知识整理一份,这两天写了一个支付宝仪表盘效果 , 一个自定义动画progressBar . 

今天来把ViewGroup相关的知识整理一下,我准备分三次来解析,这样看起来不会太累,不做太多的讲解,代码里面都有注释

先把这个章节的效果贴出来,



好的,直接看代码吗,布局文件几个章节是不一样的,这一块代码比较基础,可以慢慢往后看

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.cdl.demo.MyViewGroup
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:text="1" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:text="2" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:text="3" />

<Button
android:layout_width="80dp"
android:layout_height="80dp"
android:text="4" />
</com.cdl.demo.MyViewGroup>

</RelativeLayout>


ViewGroup代码============================================================分割线

package com.cdl.demo;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public class MyViewGroup1 extends ViewGroup {

public MyViewGroup1(Context context) {
this(context, null);
}

public MyViewGroup1(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public MyViewGroup1(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 没有适配wap_content,默认精准尺寸
measureChildren(widthMeasureSpec, heightMeasureSpec);
}

protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 控件的高度起始位置
int height = 0;
int count = getChildCount();
View child;
for (int i = 0; i < count; i++) {
// 遍历父View下面的控件,布局每一个控件为位置
child = getChildAt(i);
// 布局的四个参数,如果对参数不太理解的,可以去看一些简单的介绍.
// child.layout(left, top, right, bottom);
child.layout(0, height, child.getMeasuredWidth(), height + child.getMeasuredHeight());
// 为下一个控件设置起始位置
height += child.getMeasuredHeight();
}
}
}


代码比较简单,想要下载源码的,可以在( 三 )讲解中下载.欢迎大家点评.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息