Android自定义ViewGroup之CustomGridLayout(一)

之前写了两篇关于自定义view的文章,本篇讲讲自定义ViewGroup的实现。

我们知道ViewGroup就是View的容器类,我们经常用的LinearLayout,RelativeLayout等都是ViewGroup的子类。并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性,都是为用于告诉容器的),我们的宽度(layout_width)、高度(layout_height)、对齐方式(layout_gravity)等;于是乎,ViewGroup的职能为:给childView计算出建议的宽和高和测量模式 ;决定childView的位置;为什么只是建议的宽和高,而不是直接确定呢,别忘了childView宽和高可以设置为wrap_content,这样只有childView才能计算出自己的宽和高。

View的根据ViewGroup传入的测量值和模式,对自己宽高进行确定(onMeasure中完成),然后在onDraw中完成对自己的绘制。ViewGroup需要给View传入view的测量值和模式(onMeasure中完成),而且对于此ViewGroup的父布局,自己也需要在onMeasure中完成对自己宽和高的确定。此外,需要在onLayout中完成对其childView的位置的指定。

因为ViewGroup有很多子View,所以它的整个绘制过程相对于View会复杂一点,但是还是遵循三个步骤measure,layout,draw,我们依次说明。
本文我们来写一个类似于GridView的网格容器吧,姑且叫做CustomGridView。

自定义属性/获取属性值

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <declare-styleable name="CustomGridView">
 <attr name="numColumns" format="integer" />
 <attr name="hSpace" format="integer" />
 <attr name="vSpace" format="integer" />
 </declare-styleable>
</resources>
 public CustomGridView(Context context, AttributeSet attrs, int defStyle) {
 super(context, attrs, defStyle);
 if (attrs != null) {
  TypedArray a = getContext().obtainStyledAttributes(attrs,
   R.styleable.CustomGridView);
  colums = a.getInteger(R.styleable.CustomGridLayout_numColumns, 3);
  hSpace = a.getInteger(R.styleable.CustomGridLayout_hSpace, 10);
  vSpace = a.getInteger(R.styleable.CustomGridLayout_vSpace, 10);
  a.recycle();
 }
 }

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

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

LayoutParams

ViewGroup还有一个很重要的知识LayoutParams,LayoutParams存储了子View在加入ViewGroup中时的一些参数信息,在继承ViewGroup类时,一般也需要新建一个新的LayoutParams类,就像SDK中我们熟悉的LinearLayout.LayoutParams,RelativeLayout.LayoutParams类等一样,那么可以这样做,在你定义的ViewGroup子类中,新建一个LayoutParams类继承与ViewGroup.LayoutParams。

public static class LayoutParams extends ViewGroup.LayoutParams {
  public int left = 0;
  public int top = 0;

  public LayoutParams(Context arg0, AttributeSet arg1) {
  super(arg0, arg1);
  }

  public LayoutParams(int arg0, int arg1) {
  super(arg0, arg1);
  }

  public LayoutParams(android.view.ViewGroup.LayoutParams arg0) {
  super(arg0);
  }
 }

那么现在新的LayoutParams类已经有了,如何让我们自定义的ViewGroup使用我们自定义的LayoutParams类来添加子View呢,ViewGroup同样提供了下面这几个方法供我们重写,我们重写返回我们自定义的LayoutParams对象即可。

 @Override
 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
 return new CustomGridLayout.LayoutParams(getContext(), attrs);
 }

 @Override
 protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 }

 @Override
 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
 return new LayoutParams(p);
 }

 @Override
 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
 return p instanceof CustomGridLayout.LayoutParams;
 }

measure
在onMeasure中需要做两件事:
 •计算childView的测量值以及模式
measureChildren(widthMeasureSpec, heightMeasureSpec);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
child.measure(WidthMeasureSpec, HeightMeasureSpec);
 •设置ViewGroup自己的宽和高
测量ViewGroup的大小,如果layout_width和layout_height是match_parent或具体的xxxdp,就很简答了,直接调用setMeasuredDimension()方法,设置ViewGroup的宽高即可,如果是wrap_content,就比较麻烦了,我们需要遍历所有的子View,然后对每个子View进行测量,然后根据子View的排列规则,计算出最终ViewGroup的大小。
注意:在自定义View第一篇讲SpecMode时,曾说到UNSPECIFIED一般都是父控件是AdapterView,通过measure方法传入的模式。在这里恰好就用到了。

@Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
 int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
 int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

 //UNSPECIFIED一般都是父控件是AdapterView,通过measure方法传入的模式
 final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(sizeWidth, MeasureSpec.UNSPECIFIED);
 final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(sizeHeight, MeasureSpec.UNSPECIFIED);
 measureChildren(childWidthMeasureSpec, childHeightMeasureSpec);

 int childCount = this.getChildCount();
 int line = childCount % colums == 0 ? childCount / colums : (childCount + colums) / colums;

 //宽布局为wrap_content时,childWidth取childView宽的最大值,否则动态计算
 if (widthMode == MeasureSpec.AT_MOST) {
  for (int i = 0; i < childCount; i++) {
  View child = this.getChildAt(i);
  childWidth = Math.max(childWidth, child.getMeasuredWidth());
  }
 } else if (widthMode == MeasureSpec.EXACTLY) {
  childWidth = (sizeWidth - (colums - 1) * hSpace) / colums;
 }
 //高布局为wrap_content时,childHeight取childView高的最大值,否则动态计算
 if (heightMode == MeasureSpec.AT_MOST) {
  for (int i = 0; i < childCount; i++) {
  View child = this.getChildAt(i);
  childHeight = Math.max(childHeight, child.getMeasuredHeight());
  }
 } else if (heightMode == MeasureSpec.EXACTLY) {
  childHeight = (sizeHeight - (line - 1) * vSpace) / line;
 }

 //遍历每个子view,将它们左上角坐标保存在它们的LayoutParams中,为后面onLayout服务
 for (int i = 0; i < childCount; i++) {
  View child = this.getChildAt(i);
  LayoutParams lParams = (LayoutParams) child.getLayoutParams();
  lParams.left = (i % colums) * (childWidth + hSpace);
  lParams.top = (i / colums) * (childHeight + vSpace);
 }
 //当宽高为wrap_content时,分别计算出的viewGroup宽高
 int wrapWidth;
 int wrapHeight;
 if (childCount < colums) {
  wrapWidth = childCount * childWidth + (childCount - 1) * hSpace;
 } else {
  wrapWidth = colums * childWidth + (colums - 1) * hSpace;
 }
 wrapHeight = line * childHeight + (line - 1) * vSpace;
 setMeasuredDimension(widthMode == MeasureSpec.AT_MOST? wrapWidth:sizeWidth,heightMode == MeasureSpec.AT_MOST? wrapHeight:sizeHeight);
 }

layout
最核心的就是调用layout方法,根据我们measure阶段获得的LayoutParams中的left和top字段,也很好对每个子View进行位置排列。

@Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
 int childCount = this.getChildCount();
 for (int i = 0; i < childCount; i++) {
  View child = this.getChildAt(i);
  LayoutParams lParams = (LayoutParams) child.getLayoutParams();
  child.layout(lParams.left, lParams.top, lParams.left + childWidth, lParams.top + childHeight);
 }
 }

draw
ViewGroup在draw阶段,其实就是按照子类的排列顺序,调用子类的onDraw方法,因为我们只是View的容器,本身一般不需要draw额外的修饰,所以往往在onDraw方法里面,只需要调用ViewGroup的onDraw默认实现方法即可。不需要重写。

最后,在自定义ViewGroup中定义GridAdatper接口,以便在外部可以为ViewGroup设置适配器。

 public interface GridAdatper {
 View getView(int index);
 int getCount();
 }

 /** 设置适配器 */
 public void setGridAdapter(GridAdatper adapter) {
 this.adapter = adapter;
 // 动态添加视图
 int size = adapter.getCount();
 for (int i = 0; i < size; i++) {
  addView(adapter.getView(i));
 }
 }

并且在自定义ViewGroup中定义OnItemClickListener接口,以便在外部可以获取到childView的点击事件。

public interface OnItemClickListener {
 void onItemClick(View v, int index);
 }

 public void setOnItemClickListener(final OnItemClickListener listener) {
 if (this.adapter == null)
  return;
 for (int i = 0; i < adapter.getCount(); i++) {
  final int index = i;
  View view = getChildAt(i);
  view.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
   listener.onItemClick(v, index);
  }
  });
 }
 }

使用自定义的CustomViewGroup

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.hx.customgridview"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#303030"
 android:orientation="vertical" >

 <com.hx.customgridview.CustomGridLayout
 android:id="@+id/gridview"
 android:layout_width="200dp"
 android:layout_height="300dp"
 android:background="#1e1d1d"
 app:hSpace="10"
 app:vSpace="10"
 app:numColumns="3"/>
</LinearLayout>

grid_item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="vertical" >
 <ImageView
 android:id="@+id/iv"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:scaleType="fitXY"/>
</LinearLayout>

Java文件:

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 grid = (CustomGridLayout) findViewById(R.id.gridview);
 grid.setGridAdapter(new GridAdatper() {
  @Override
  public View getView(int index) {
  View view = getLayoutInflater().inflate(R.layout.grid_item, null);
  ImageView iv = (ImageView) view.findViewById(R.id.iv);
  iv.setImageResource(srcs[index]);
  return view;
  }

  @Override
  public int getCount() {
  return srcs.length;
  }
 });
 grid.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(View v, int index) {
  Toast.makeText(MainActivity.this, "item="+index, Toast.LENGTH_SHORT).show();
  }
 });
 }
}

运行后效果图如下:

改变一下布局:

<com.hx.customgridview.CustomGridLayout
  android:id="@+id/gridview"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="#1e1d1d"
  app:hSpace="10"
  app:vSpace="10"
  app:numColumns="3"/>

再改变

<com.hx.customgridview.CustomGridLayout
  android:id="@+id/gridview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#1e1d1d"
  app:hSpace="10"
  app:vSpace="10"
  app:numColumns="3"/>

再变

<com.hx.customgridview.CustomGridLayout
  android:id="@+id/gridview"
  android:layout_width="wrap_content"  

  android:layout_height="wrap_content"
  android:background="#1e1d1d"
  app:hSpace="10"
  app:vSpace="10"
  app:numColumns="4"/>

Demo下载地址:http://xiazai.jb51.net/201609/yuanma/CustomGridLayout(jb51.net).rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android实现热门标签的流式布局

    一.概述: 在日常的app使用中,我们会在android 的app中看见 热门标签等自动换行的流式布局,今天,我们就来看看如何 自定义一个类似热门标签那样的流式布局吧(源码下载在下面最后给出) 类似的自定义布局.下面我们就来详细介绍流式布局的应用特点以及用的的技术点: 1.流式布局的特点以及应用场景     特点:当上面一行的空间不够容纳新的TextView时候,     才开辟下一行的空间 原理图:    场景:主要用于关键词搜索或者热门标签等场景 2.自定义ViewGroup,重点重写下面两

  • Android简单实现自定义流式布局的方法

    本文实例讲述了Android简单实现自定义流式布局的方法.分享给大家供大家参考,具体如下: 首先来看一下 手淘HD - 商品详情 - 选择商品属性 页面的UI 商品有很多尺码,而且展现每个尺码所需要的View的大小也不同(主要是宽度),所以在从服务器端拉到数据之前,展现所有尺码所需要的行数和每一行的个数都无法确定,因此不能直接使用GridView或ListView. 如果使用LinearLayout呢? 一个LinearLayout只能显示一行,如果要展示多行,则每一行都要new一个Linear

  • android多行标签热点示例

    复制代码 代码如下: package com.test.mytest.widget; import java.util.List; import android.content.Context;import android.os.Handler;import android.util.AttributeSet;import android.widget.LinearLayout;import android.widget.TextView; public class MutipleLabelLa

  • 解析在Android中为TextView增加自定义HTML标签的实现方法

    Android中的TextView,本身就支持部分的Html格式标签.这其中包括常用的字体大小颜色设置,文本链接等.使用起来也比较方便,只需要使用Html类转换一下即可.比如: textView.setText(Html.fromHtml(str)); 然而,有一种场合,默认支持的标签可能不够用.比如,我们需要在textView中点击某种链接,返回到应用中的某个界面,而不仅仅是网络连接,如何实现? 经过几个小时对android中的Html类源代码的研究,找到了解决办法,并且测试通过. 先看Htm

  • Android中使用include标签和merge标签重复使用布局

    尽管Android提供了各种组件来实现小而可复用的交互元素,你也可能因为布局需要复用一个大组件.为了高效复用完整布局,你可以使用<include/>和<merge/>标签嵌入另一个布局到当前布局.所以当你通过写一个自定义视图创建独立UI组件,你可以放到一个布局文件里,这样更容易复用. 复用布局因为其允许你创建可复用的复杂布局而显得非常强大.如,一个 是/否 按钮面板,或带描述文本的自定义进度条.这同样意味着,应用里多个布局里共同的元素可以被提取出来,独立管理,然后插入到每个布局里.

  • Android自定义ViewGroup之实现FlowLayout流式布局

    整理总结自鸿洋的博客:http://blog.csdn.net/lmj623565791/article/details/38352503/  一.FlowLayout介绍  所谓FlowLayout,就是控件根据ViewGroup的宽,自动的往右添加,如果当前行剩余空间不足,则自动添加到下一行.有点像所有的控件都往左飘的感觉,第一行满了,往第二行飘~所以也叫流式布局.Android并没有提供流式布局,但是某些场合中,流式布局还是非常适合使用的,比如关键字标签,搜索热词列表等,比如下图: git

  • Android自定义ViewGroup之FlowLayout(三)

    本篇继续来讲自定义ViewGroup,给大家带来一个实例:FlowLayout.何为FlowLayout,就是控件根据ViewGroup的宽,自动的往右添加,如果当前行剩余空间不足,则自动添加到下一行,所以也叫流式布局.Android并没有提供流式布局,但是某些场合中,流式布局还是非常适合使用的,比如关键字标签,搜索热词列表等,比如下图: 定义FlowLayout LayoutParams,onLayout的写法都和上一篇讲WaterfallLayout一模一样,在此不再赘述了,没看过的可以参照

  • Android开发常用标签小结

    本文较为详细的总结了Android开发常用标签.分享给大家供大家参考.具体如下: android中inputType android中inputType属性在EditText输入值时启动的虚拟键盘的风格有着重要的作用.这也大大的方便的操作.有时需要虚拟键盘只为字符或只为数字.所以inputType尤为重要. android:paddingLeft与android:layout_marginLeft的区别 当按钮分别设置以上两个属性时,得到的效果是不一样的. android:paddingLeft

  • Android自定义ViewGroup之WaterfallLayout(二)

    上一篇我们学习了自定义ViewGroup的基本步骤,并做了一个CustomGridLayout的实例,这篇我们继续来说说自定义ViewGroup. Android中当有大量照片需要展示的时候,我们可以用GridView作为照片墙,但是GridView太整齐了,有时候不规则也是一种美,瀑布流模型就是这样一个不规则的展示墙,接下来我们尝试用自定义ViewGroup来实现瀑布流. 实现瀑布流的方式也有很多,下面我们一一道来: 一.继承ViewGroup 其实这种实现方式我们只需要在上篇博客的基础上稍作

  • android配合viewpager实现可滑动的标签栏示例分享

    复制代码 代码如下: package com.example.playtabtest.view; import com.example.playtabtest.R; import android.app.Activity;import android.content.Context;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;impor

随机推荐