最近,谷歌开源了一个流式排版库“FlexboxLayout功能强大,支持多种排版方式,如各种方向的自动换行等,具体资料各位可搜索学习^ _ ^ .
由于我的项目中,只需要从左到右S型的自动换行,需求效果图如下:
使用FlexboxLayout这个框架未免显得有些臃肿,所以自己动手写了一个流式ViewGroup。
<>强安卓中自定义ViewGroup的步骤是:强>
1。新建一个类,继承ViewGroup
2。重写构造方法
3。重写onMeasure, onLayout方法
onMeasuer方法里一般写测量子视图宽高,确定此控件宽高的代码;onLayout方法则是确定子视图如何摆放(排版)。
代码如下:
进口android.content.Context; 进口android.util.AttributeSet; 进口android.view.View; 进口android.view.ViewGroup; 公开课FlexBoxLayout延伸ViewGroup { 私人int mScreenWidth; 私人int horizontalSpace verticalSpace; 私人浮动mDensity;//设备密度,用于将dp转为px 公共FlexBoxLayout(上下文语境){ 这(上下文,null); } 公共FlexBoxLayout(上下文语境,AttributeSet attrs) { 超级(上下文,attrs);//获取屏幕宽高,设备密度 .widthPixels .getDisplayMetrics mScreenWidth=context.getResources () (); .density .getDisplayMetrics mDensity=context.getResources () (); } @Override 保护空白> & lt; com.zengd.FlexBoxLayout android: id=癅 + id/flexBoxLayout” android: layout_width=" match_parent " android: layout_height=癿atch_parent”比; & lt; !——这里写子视图,也可代码动态添加——比; …… & lt;/com.zengd.FlexBoxLayout> >之前<强>活动里的代码:强>
FlexBoxLayout FlexBoxLayout=(FlexBoxLayout) findViewById (R.id.flex_box_layout); flexBoxLayout.setHorizontalSpace(10);//不设置默认为0 flexBoxLayout.setVerticalSpace(10);//不设置默认为0运行效果如图:
本项目演示地址:
https://github.com/zengd0/FlexBoxLayout
<强> Android流式布局(修改版)当达到两行,隐藏多余的强>
我就废话不多说了,还是直接看代码吧!
公开课SearchLayout LinearLayout{延伸 私人最终int mParentWidth; 私人textSize浮动; 私人boolean输入textColor; 私人布尔背景; 私人布尔isHide=true; 公共空间setHide(布尔隐藏){ isHide=隐藏; } 公共SearchLayout(上下文语境,AttributeSet attrs) { 超级(上下文,attrs);//获取屏幕的宽度 .getDisplayMetrics DisplayMetrics指标=context.getResources () (); mParentWidth=指标。widthPixels dip2px (16);//自定义属性 TypedArray数组=上下文。obtainStyledAttributes (attrs R.styleable.SearchLayout); 背景=array.getBoolean (R.styleable.SearchLayout_Sear_background、假); 输入textColor=array.getBoolean (R.styleable。SearchLayout_Sear_textColor、假); textSize=array.getDimension (R.styleable。SearchLayout_Sear_textSize, 0);//方向为纵向 setOrientation(垂直); }//移除子控件 公共空间removeView () { removeAllViews (); }//流式布的局 公共空间setData (List数据){ 如果(data.isEmpty ()) { 返回; }//获取一个子布的局 LinearLayout LinearLayout=getLinearLayout (); for (int i=0;我& lt;data.size ();我+ +){//标题 最终字符串名称=data.get(我);//已存在的宽度 int numBar=0;//子控件的个数 int数=linearLayout.getChildCount (); for (int j=0;j & lt;计数;j + +) {//一个一个获取 ThemeTextView textView=(ThemeTextView) linearLayout.getChildAt (j);//获取左外边距 LayoutParams params=(LayoutParams) textView.getLayoutParams (); int leftWidth=params.leftMargin; int rightWidth=params.rightMargin;//获取宽高 getMeasuredHeight textView.measure (getMeasuredWidth () ());//计算已存在的宽度 numBar +=textView.getMeasuredWidth () + leftWidth + rightWidth; }//获取一个子控件 ThemeTextView文本=getText ();//给每一个控件设置点击事件 text.setOnClickListener (new> & lt; declare-styleable name=" SearchLayout比; & lt; attr=name=" Sear_textSize "格式"维度"/比; & lt; attr name==安级?癝ear_textColor”格式比; & lt; attr name==安级?癝ear_background”格式比; & lt;/declare-styleable> Android自定义流式布局/自动换行布局实例