Android 自定义viewGroup学习之FlowLayout的实现
来源:互联网 发布:网站源码加密破解 编辑:程序博客网 时间:2024/04/29 08:54
Android 自定义viewGroup学习之FlowLayout的实现
最近在学习自定义的viewGroup,刚接触,是真的难,看了洪洋大神的博客,收益多多,现在记录一下我对洪洋大神这篇文章Android 自定义ViewGroup 实战篇 -> 实现FlowLayout的理解。
首先,viewGroup存在的目的是对其子view的管理,为其子view添加显示、响应的规则。因此,自定义的viewGroup需要重写onMeasure()方法来对子view进行测量,重写onLayout()方法来确定子view的位置,重写onTouchEvent()来添加响应事件。
所以,自定义viewGroup大致有以下步骤:
1、重写onMeasure()来对子view进行测量
2、重写onLayout()方法来确定子view的位置
3、必要时重写onTouchEvent()来添加响应事件。
一、创建一个类继承ViewGroup
实现它的三个构造方法:
public FlowLayoutTrain(Context context) { this(context,null); } public FlowLayoutTrain(Context context, AttributeSet attrs) { this(context, attrs,0); } public FlowLayoutTrain(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }
其中有一个参数的构造方法,还有两个、三个参数的构造方法,让一个参数的构造方法去调用两个参数的构造方法,让两个参数的构造方法去调用三个参数的构造方法,这样无论使用哪个构造方法产生的实例,最终调用的代码都是一致的。
二:重写onMeasure()方法
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 获得它的父容器为它设置的测量模式和大小 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec); Log.e("TAG", sizeWidth + "," + sizeHeight); // 如果是warp_content情况下,记录宽和高 int width = 0; int height = 0; /** * 记录每一行的宽度,width不断取最大宽度 */ int lineWidth = 0; /** * 每一行的高度,累加至height */ int lineHeight = 0; int cCount = getChildCount(); // 遍历每个子元素 for (int i = 0; i < cCount; i++) { View child = getChildAt(i); // 测量每一个child的宽和高 measureChild(child, widthMeasureSpec, heightMeasureSpec); // 得到child的lp MarginLayoutParams lp = (MarginLayoutParams) child .getLayoutParams(); // 当前子空间实际占据的宽度 int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; // 当前子空间实际占据的高度 int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; /** * 如果加入当前child,则超出最大宽度,则的到目前最大宽度给width,类加height 然后开启新行 */ if (lineWidth + childWidth > sizeWidth) { width = Math.max(lineWidth, childWidth);// 取最大的 lineWidth = childWidth; // 重新开启新行,开始记录 // 叠加当前高度, height += lineHeight; // 开启记录下一行的高度 lineHeight = childHeight; } else // 否则累加值lineWidth,lineHeight取最大高度 { lineWidth += childWidth; lineHeight = Math.max(lineHeight, childHeight); } // 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较 if (i == cCount - 1) { width = Math.max(width, lineWidth); height += lineHeight; } } setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height); }
洪洋大神已经注释的很清楚了,真是好有爱的大神。
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec); int sizeHeight = MeasureSpec.getSize(heightMeasureSpec); int modeWidth = MeasureSpec.getMode(widthMeasureSpec); int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
这四行代码获得它的父容器为它设置的测量模式和大小,如果是viewGroup设置为match_parent或者说模式为MeasureSpec.EXACTLY时直接使用sizeWidth和sizeHeight,即父ViewGroup传入的宽和高。反之,就要根据所有childView的测量得出的宽和高得到该ViewGroup如果设置为wrap_content时的宽和高。
这就有了最后的一句代码:
setMeasuredDimension((modeWidth == MeasureSpec.EXACTLY) ? sizeWidth : width, (modeHeight == MeasureSpec.EXACTLY) ? sizeHeight : height);
这里说一下ViewGroup的layoutParams
这里重写了方法:
@Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(),attrs); }
指定了ViewGroup的layoutParams为MaginLayoutParams,那么,所有的子view.getLayoutParmas()得到的layoutParams就是子view所在父布局的layoutparams,在这里就是MarginLayoutParams。
再看看子view的宽度和高度:
// 当前子空间实际占据的宽度 int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin; // 当前子空间实际占据的高度 int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
是不是一目了然呢。(图片是childview.getMeasureWidth哈,写差了Width)
而事实上也是如此的,我从控制台打印出子View的left,top,right,bottom
Log.e("TAG", child + " , l = " + lc + " , t = " + tc + " , r =" + rc + " , b = " + bc);
第一个子view的left=10,第二个子view的left=第一个子view的childWidth+第二个子view的leftMargin,也就是134+10+10=154,
验证对了,其他同理。对这些边距,上下左右都明白了,看起来就不吃力了。
还有这个:
if (lineWidth + childWidth > sizeWidth) { width = Math.max(lineWidth, width);// 取最大的 lineWidth = childWidth; // 重新开启新行,开始记录 // 叠加当前高度, height += lineHeight; // 开启记录下一行的高度 lineHeight = childHeight; } else // 否则累加值lineWidth,lineHeight取最大高度 { lineWidth += childWidth; lineHeight = Math.max(lineHeight, childHeight); } // 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较 if (i == cCount - 1) { width = Math.max(width, lineWidth); height += lineHeight; }
特别注意要加上最后一个if条件语句。当不换行时,lineWidth随着子view的增加不断变大( lineWidth += childWidth;),当lineWidth再加上一个childWidth时超过了sizeWidth(lineWidth + childWidth > sizeWidth)时就要换行,这时就将叠加当前的高度,重新开启一行,那么,如果达不到换行的要求,是不是本行的高度就没有叠加进去了呢?所以,无论怎样,到达最后一个控件都要再叠加一次高度把最后一行的高度加进去。
三:重写onLayout()方法
onlayout()方法就是要确定子view的位置,何时换行等等
/** * 存储所有的View,按行记录 */ private List<List<View>> mAllViews = new ArrayList<List<View>>(); /** * 记录每一行的最大高度 */ private List<Integer> mLineHeight = new ArrayList<Integer>(); @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { mAllViews.clear(); mLineHeight.clear(); int width = getWidth(); int lineWidth = 0; int lineHeight = 0; // 存储每一行所有的childView List<View> lineViews = new ArrayList<View>(); int cCount = getChildCount(); // 遍历所有的孩子 for (int i = 0; i < cCount; i++) { View child = getChildAt(i); MarginLayoutParams lp = (MarginLayoutParams) child .getLayoutParams(); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); // 如果已经需要换行 if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width) { // 记录这一行所有的View以及最大高度 mLineHeight.add(lineHeight); // 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView mAllViews.add(lineViews); lineWidth = 0;// 重置行宽 lineViews = new ArrayList<View>(); } /** * 如果不需要换行,则累加 */ lineWidth += childWidth + lp.leftMargin + lp.rightMargin; lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin); lineViews.add(child); } // 记录最后一行 mLineHeight.add(lineHeight); mAllViews.add(lineViews); int left = 0; int top = 0; // 得到总行数 int lineNums = mAllViews.size(); for (int i = 0; i < lineNums; i++) { // 每一行的所有的views lineViews = mAllViews.get(i); // 当前行的最大高度 lineHeight = mLineHeight.get(i); Log.e(TAG, "第" + i + "行 :" + lineViews.size() + " , " + lineViews); Log.e(TAG, "第" + i + "行, :" + lineHeight); // 遍历当前行所有的View for (int j = 0; j < lineViews.size(); j++) { View child = lineViews.get(j); if (child.getVisibility() == View.GONE) { continue; } MarginLayoutParams lp = (MarginLayoutParams) child .getLayoutParams(); //计算childView的left,top,right,bottom int lc = left + lp.leftMargin; int tc = top + lp.topMargin; int rc =lc + child.getMeasuredWidth(); int bc = tc + child.getMeasuredHeight(); Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r =" + rc + " , b = " + bc); child.layout(lc, tc, rc, bc); left += child.getMeasuredWidth() + lp.rightMargin + lp.leftMargin; } left = 0; top += lineHeight; } }
首先,看一下这个:
mAllViews.clear(); mLineHeight.clear();
这是因为在实现过程中会多次调用onLayout()这个方法,所以每次需要clear一下。
对于这个:
/** * 存储所有的View,按行记录 */ private List<List<View>> mAllViews = new ArrayList<List<View>>(); /**
对于List<’List<’View>>,通俗的来讲,List<>是装东西的箱子,List’<’List<>>是装箱子的箱子。
而在这里呢,List’<’View>装的是每一行的View集合,List<’List<’View>>装的是每行所有View的List集合。
计算的View的位置相信大家通过onMeasure()都能看懂了吧。
//计算childView的left,top,right,bottom int lc = left + lp.leftMargin; int tc = top + lp.topMargin; int rc =lc + child.getMeasuredWidth(); int bc = tc + child.getMeasuredHeight(); Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r =" + rc + " , b = " + bc); child.layout(lc, tc, rc, bc); left += child.getMeasuredWidth() + lp.rightMargin + lp.leftMargin;
这一块代码就是设置子view的位置,从上面我上传的那张图可以知道,当没有换行时,子view是按从左到右排列的。这里再附上一张view的(left、top、right、bottom)的具体位置图(感谢原图作者):
接着看:
int left = 0; int top += lineHeight;
当换行后,left归0,高度叠加一行,重新对下一行的view进行排列,就这样将所有的view排列完成。
至此,就完成了自定义viewGroup的代码,接下来测试。
四:测试
1、先在res->drawable文件夹下新建word_bg.xml,定义一些样式
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#e7e7e7"/> <corners android:radius="30dp"/> <padding android:top="2dp" android:bottom="2dp" android:right="10dp" android:left="10dp"> </padding></shape>
2、再写一个word.xml
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HelloWorld" android:background="@drawable/word_bg" android:layout_margin="5dp"></TextView>
3、在主布局文件里调用
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.calolin.testdemo.FlowLayoutTrain android:id="@+id/flowlayout" android:layout_width="wrap_content" android:layout_height="wrap_content"> </com.calolin.testdemo.FlowLayoutTrain>
3、在mainActivity里:
public class MainActivity extends Activity { String [] tv_datas=new String[]{ "程序媛","加薪","IT行业","过劳死","年薪百万","我爱妈妈" ,"吴大头" }; private FlowLayoutTrain mflowlayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.flow_layout); mflowlayout= (FlowLayoutTrain) findViewById(R.id.flowlayout); LayoutInflater mInflater=LayoutInflater.from(this); for (int i=0;i<tv_datas.length;i++){ TextView tv= (TextView) mInflater.inflate(R.layout.tv,mflowlayout,false); tv.setText(tv_datas[i]); mflowlayout.addView(tv); }}
酱酱:
完了。新手,有错误的请多指教。
- Android 自定义viewGroup学习之FlowLayout的实现
- Android 自定义ViewGroup 实现FlowLayout
- Android 自定义ViewGroup 实现FlowLayout
- Android 自定义ViewGroup之实现FlowLayout-标签流容器
- Android 自定义ViewGroup之实现FlowLayout-标签流容器
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- 【Android】 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Android 自定义ViewGroup 实战篇 -> 实现FlowLayout
- Windows下在同一机器上配置多个tomcat^_^
- mysql创建存储过程
- 门面模式
- HDU 5773 The All-purpose Zero 16多校4 贪心 LCA
- 关于vs提示_CRT_SECURE_NO_WARNINGS 警告的问题
- Android 自定义viewGroup学习之FlowLayout的实现
- NOI2007货币兑换CASH 斜率DP
- 3D轮播图
- POJ 3274 Gold Balanced Lineup 数组Hash
- poj 2054 Color a Tree 贪心
- unity 常用/有用attributes
- Windows下搭建Flask环境
- 百练 openjudge 开餐馆(动态规划)
- xUtils3