Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定义 View 系列教程 05:两个经典示例的深度拆解

編輯:關於 Android 程式設計

此前结合源码,我们分析完了自定义 View 的三个阶段:measure、layout、draw。那么,自定义 View 究竟有哪几种常见的方式呢?

一、直接继承自 View

采用这种方式实现自定义 View 时,核心操作通常都集中在 onDraw() 之中。但请务必留意:在分析 measure 部分源码时我们曾提到,若直接继承自 View,则需要在 onMeasure() 中处理 view 大小为 wrap_content 的情形,否则这种情况下的大小会与 match_parent 无异。除此之外,还需注意对 padding 的处理。

二、继承自系统已有的 View

比如常见的 TextView、Button 等等。若采用这种方式,我们只需在系统控件的基础上做些调整与扩展即可,而且无需自己去支持 wrap_content 与 padding。

三、直接继承自 ViewGroup

若采用这种方式实现自定义 View,请注意两个问题:

其一:在 onMeasure() 中实现对 wrap_content 的支持,这一点与直接继承自 View 是一致的。

其二:在 onMeasure() 与 onLayout 中,需要处理自身的 padding 以及子 View 的 margin。

四、继承自系统已有的 ViewGroup

比如 LinearLayout、RelativeLayout 等等。若采用这种方式,那么上述第三点提到的两个问题便无需过多顾虑了,省事许多。

下面,我们举两个例子来加以说明。


示例一:可折叠展开的 CollapseView

先看第一个例子,效果如下图:

对于该效果,主要描述如下:点击 Title 部分展开图片,再次点击则收缩图片;图片的收缩与展开皆渐次进行,并在切换过程中以动画切换右侧箭头的方向。

明确了效果,我们便来拆解一下这个小功能:

1. 控件由数字、标题、箭头、图片四部分组成;

2. 点击标题后逐渐显示或隐藏图片;

3. 图片切换过程中伴随着箭头方向的改变。

理清这些,就该动手写代码了。先来看这个控件的布局文件:

           

请注意,这里将显示图片的容器 contentRelativeLayout 设为了 gone。为何要这么做呢?因为进入应用后是看不到图片部分的,唯有点击后方可见。你大概已经猜到了:图片的隐藏与显示,正是通过改变容器的 visibility 来实现的。没错!那么,图片的渐次显示与隐藏、以及箭头的旋转又是怎么做到的呢?请看该控件的具体实现。

 package com.stay4it.testcollapseview; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * 原創作者: * 谷哥的小弟 * * 博客地址: * https://blog.csdn.net/lfdfhl */ public class CollapseView extends LinearLayout { private long duration = 350; private Context mContext; private TextView mNumberTextView; private TextView mTitleTextView; private RelativeLayout mContentRelativeLayout; private RelativeLayout mTitleRelativeLayout; private ImageView mArrowImageView; int parentWidthMeasureSpec; int parentHeightMeasureSpec; public CollapseView(Context context) { this(context, null); } public CollapseView(Context context, AttributeSet attrs) { super(context, attrs); mContext=context; LayoutInflater.from(mContext).inflate(R.layout.collapse_layout, this); initView(); } private void initView() { mNumberTextView=(TextView)findViewById(R.id.numberTextView); mTitleTextView =(TextView)findViewById(R.id.titleTextView); mTitleRelativeLayout= (RelativeLayout) findViewById(R.id.titleRelativeLayout); mContentRelativeLayout=(RelativeLayout)findViewById(R.id.contentRelativeLayout); mArrowImageView =(ImageView)findViewById(R.id.arrowImageView); mTitleRelativeLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { rotateArrow(); } }); collapse(mContentRelativeLayout); } public void setNumber(String number){ if(!TextUtils.isEmpty(number)){ mNumberTextView.setText(number); } } public void setTitle(String title){ if(!TextUtils.isEmpty(title)){ mTitleTextView.setText(title); } } public void setContent(int resID){ View view=LayoutInflater.from(mContext).inflate(resID,null); RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); view.setLayoutParams(layoutParams); mContentRelativeLayout.addView(view); } public void rotateArrow() { int degree = 0; if (mArrowImageView.getTag() == null || mArrowImageView.getTag().equals(true)) { mArrowImageView.setTag(false); degree = -180; expand(mContentRelativeLayout); } else { degree = 0; mArrowImageView.setTag(true); collapse(mContentRelativeLayout); } mArrowImageView.animate().setDuration(duration).rotation(degree); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); parentWidthMeasureSpec=widthMeasureSpec; parentHeightMeasureSpec=heightMeasureSpec; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } // 展開 private void expand(final View view) { WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(outMetrics); view.measure(parentWidthMeasureSpec, parentHeightMeasureSpec); final int measuredWidth = view.getMeasuredWidth(); final int measuredHeight = view.getMeasuredHeight(); view.setVisibility(View.VISIBLE); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if(interpolatedTime == 1){ view.getLayoutParams().height =measuredHeight; }else{ view.getLayoutParams().height =(int) (measuredHeight * interpolatedTime); } view.requestLayout(); } @Override public boolean willChangeBounds() { return true; } }; animation.setDuration(duration); view.startAnimation(animation); } // 折疊 private void collapse(final View view) { final int measuredHeight = view.getMeasuredHeight(); Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { if (interpolatedTime == 1) { view.setVisibility(View.GONE); } else { view.getLayoutParams().height = measuredHeight - (int) (measuredHeight * interpolatedTime); view.requestLayout(); } } @Override public boolean willChangeBounds() { return true; } }; animation.setDuration(duration); view.startAnimation(animation); } } 

现就代码中的主要操作做一些分析与介绍:

1. 控件提供 setNumber() 方法用于设置最左侧的数字(参见第 62-66 行);

2. 控件提供 setTitle() 方法用于设置标题(参见第 68-72 行);

3. 控件提供 setContent() 方法用于设置隐藏与显示的内容(参见第 74-80 行)。请留意,该方法的参数是一个布局文件的 ID,所以要显示与隐藏的东西只要写在一个布局文件中即可,如此一来便灵活多了,可根据实际需求实现不同的布局。比如在本文示例中,我在一个布局文件里只放了一个 ImageView,再把这个布局文件的 ID 传给该方法即可。

4. 实现 Title 部分的 Click 监听(参见第 51-56 行),在监听到 Click 事件后显示或隐藏 content 部分。

接着看 content 部分的显示(参见第 110-138 行)。这里遇到一个难题:这个 content 会占多大的空间呢?

不妨打个比方:小狗一秒跑 1 米(即速度为 1m/s),请问它跑完这段路要多少时间?看到这个问题,是不是觉得有点「脑残」——路程长短都没告诉你,怎么知道要跑多久?

没错。我们在这里根本不知道这个 View(比如 content)有多高多宽,自然也就无从得知它要占多大的空间!那怎么办呢?在这里就按最直接粗暴的方式来——遇到问题,解决问题!找出该 View 的宽和高!

前面分析 View 的 measure 阶段时我们知道,这些控件的宽高是由系统测量的,在此之后我们只需利用 getMeasuredWidth() 与 getMeasuredHeight() 即可。但这个控件的 visibility 原本是 GONE 的,系统在 measure 阶段根本不会去测量它的宽高,所以现在需要我们自己手动测量。代码如下:

view.measure(parentWidthMeasureSpec, parentHeightMeasureSpec);

获取到 view 的宽高后,便借助动画实现 content 的渐次展开(参见第 119-137 行)。动画的 interpolatedTime 会在一定时间内(duration)从 0 变化到 1,因此

measuredHeight * interpolatedTime

便表示了 content 的高从 0 到 measuredHeight 的逐次变化;在这一变化过程中不断调用

view.requestLayout();

刷新界面,如此便达成了预期的效果。

content 部分的隐藏(参见第 141-161 行),其原理与之前的逐次显示如出一辙,不再赘述。

箭头的转向(参见第 83-95 行)则比较简单,这里直接用属性动画(ViewPropertyAnimator)让箭头旋转即可。

示例小结:本 demo 主要采用手动测量 View 的方式获取 View 的大小。


示例二:流式布局 FlowLayout

再看第二个例子,效果如下图:

这个流式布局(FlowLayout)大家或许见过,它常用来做标签的显示。而且在标签的展示过程中,若这一行没有足够的空间显示下一个标签,便会先自动换行,然后再添加新的标签。

下面我们就来看看它是怎么实现的:

 package com.stay4it.testflowlayout; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * 原創作者: * 谷哥的小弟 * * 博客地址: * https://blog.csdn.net/lfdfhl */ public class MyFlowLayout extends ViewGroup{ private int verticalSpacing = 20; public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int widthUsed = paddingLeft + paddingRight; int heightUsed = paddingTop + paddingBottom; int childMaxHeightOfThisLine = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childUsedWidth = 0; int childUsedHeight = 0; measureChild(child,widthMeasureSpec,heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); LayoutParams childLayoutParams = child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin; childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin; if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else { heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); LayoutParams childLayoutParams = child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; int childLeftMargin = marginLayoutParams.leftMargin; int childTopMargin = marginLayoutParams.topMargin; int childRightMargin = marginLayoutParams.rightMargin; int childBottomMargin = marginLayoutParams.bottomMargin; childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth; childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight; if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } } 

现就代码中的主要操作做一些分析与介绍:

1. 控件继承自 ViewGroup(参见第 15 行)。系统自带的布局(如 LinearLayout)很难满足标签自动换行的功能,因此继承 ViewGroup 来实现所需的设计与逻辑。

2. 重写 onMeasure()(参见第 22-71 行)。

2.1 获取 View 宽和高的 mode 与 size(参见第 23-26 行)。此处 widthSpecSize 表示 View 的宽,该值在判断是否需要换行时会用到。

2.2 计算 View 在水平方向与垂直方向上已经占用的大小(参见第 33-34 行)。这些已占用的大小,主要指 View 的 padding 值。

2.3 测量每个子 View 的宽和高(参见第 38-67 行),这一步是重中之重,需要测量出每个子 View 的大小,从而计算出该控件的高度。

在具体分析代码之前,我们先厘清几个问题:

第一点:我们常说测量每个子 View 的宽高,是为了把每个子 View 的宽累加起来得到父 View 的宽、把高累加起来得到父 View 的高。而在此,控件的宽就是屏幕的宽,所以无需累加每个子 View 的宽,但要利用子 View 的宽来判断换行的时机;至于控件的高,则仍需将每个子 View 的高相累加。

第二点:如何判断需要换行显示新的 tag 呢?若「这一行已占用的宽度 + 即将显示的子 View 的宽度 > 该行总宽度」,那就要考虑换行显示该 tag。

第三点:若十个人站成一排,那么这个队伍的高度由谁决定呢?当然是这排人里个子最高的人。同理,几个 tag 摆放在同一行,这一行的高度便由最高的 tag 决定;然后将每一行的高度相加,就是 View 的总高了。

明白了这些,再看代码就容易多了:

第一步:利用 measureChild() 测量子 View(参见第 43 行);

第二步:计算子 View 需要占用的宽和高(childUsedWidth 与 childUsedHeight,参见第 51-52 行);

第三步:判断并处理是否需要换行(参见第 54-63 行);

第四步:利用 setMeasuredDimension() 设置 View 的宽和高(参见第 70 行)。

3. 重写 onLayout()(参见第 75-133 行)。在 onMeasure 中已对每个子 View 进行了测量,该阶段需要把每个子 View 摆放到合适的位置,因此核心是确定每个子 View 的 left、top、right、bottom。在此过程中同样要考虑换行问题,思路也与 measure 阶段类似,故不再赘述。

写完了这个自定义控件的代码,又该如何使用呢?只需在布局中像使用普通控件一样引入它,再往里添加若干带 margin 的子 View 即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved