我是靠谱客的博主 帅气发带,这篇文章主要介绍简单的自定义View总结自定义View自定义ViewGroup,现在分享给大家,希望可以做个参考。

自定义View在Android中是很重要的,总结一些简单自定义View的知识点吧

最简单用的就是在布局中定义属性:

1、我们需要再style.xml文件中生命我们的自定义属性:

复制代码
1
2
3
4
5
<resources> <declare-styleable name="MyView"> <attr name="default_size" format="dimension" /> </declare-styleable> </resources>

2、在布局中定义我们的属性

3、在自定义View中把布局中的属性取出来

复制代码
1
2
3
4
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100); //最后记得将TypedArray对象回收 a.recycle();

自定义View的三个重要步骤:measure、layout、draw

自定义View不需要重写layout,自定义ViewGroup需要重写layout

自定义View

onMeasure()

首先我们需要测量来知道长和宽从而确定View需要多大的空间

MeasureSpec:直译的话就是测量规格的意思,在measure过程中有着非常重要的作用

  1. MeasureSpec封装了父布局传递给子View的要求
  2. MeasureSpec可以表示宽高
  3. MeasureSpec由size和mode组成

measureSpec是一个32位的int型数据

  • 高2位代表SpecMode,测量模式
  • 低30位代表在该模式下的大小

获取模式和尺寸:

复制代码
1
2
3
4
int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); // 反向生成 int measureSpec = MeasureSpec.makeMeasureSpec(size, mode);

SpecMode:

复制代码
1
2
3
4
5
6
7
8
9
// 精确的、、、父容器已经检测出子View所需要的精确大小,如100dp, match_parent // 大小即为SpecSize MeasureSpec.EXACTLY // 最多、充其量、、、父容器未能检测出子View所需要的大小,但指定了一个可用大小,如wrap_content // 不能超过SpecSize MeasureSpec.AT_MOST // 不明确的、、、父容器不对View的大小做限制 MeasureSpec.UNSPECIFIED // 此模式一般用于Android内部,比如ScrollView、ListView等控件,不做讨论了

最后在onMeasure()方法中通过setMeasureDimenion()来设置宽高

复制代码
1
// 根据widthMeasureSpec和heightMeasureSpec的mode和size来决定最后setMeasuredDimension()的值

onDraw()

比较简单了,在canvas上进行绘制,用Paint,这里不说了

自定义ViewGroup

1、知道各个子View的大小,决定出ViewGroup的大小

2、摆放子View的大小,对号入座

复制代码
1
2
3
4
5
6
7
8
9
10
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //将所有的子View进行测量,这会触发每个子View的onMeasure函数 //注意要与measureChild区分,measureChild是对单个view进行测量 measureChildren(widthMeasureSpec, heightMeasureSpec); // todo // 根据widthMeasureSpec和heightMeasureSpec来决定大小 setMeasuredDimension(xxx,xxx); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int count = getChildCount(); //将子View逐个摆放 for (int i = 0; i < count; i++) { View child = getChildAt(i); // todo // 进行各种操作摆放 child.layout(xxx, xxx, xxx, xxx); } }

总结

只是简单的将自定义View最最最入门的东西总结一下,相当于一个笔记

最后

以上就是帅气发带最近收集整理的关于简单的自定义View总结自定义View自定义ViewGroup的全部内容,更多相关简单内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部