赞
踩
前两天突发一个bug,我在ScrollView中嵌套了一个GridView(已经重写了onMeasure方法),GridView的高度是wrap_content,在我更新adapter的时候GridView的高度竟然会时高时低,搞得我一脸懵逼,最终找到原因:
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2 + expandHeight,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
不知道是什么历史原因,高度的测量模式竟然被我修改成这个样子,影响了MeasureSpec.AT_MOST模式下的高度测量,并且问题非必现。
ScrollView嵌套GridView,为了解决手势冲突问题,需要设置GridView高度为wrap_content,我遇到的有两种解决方案:
所有的不满终于在这次爆发,决定实现一个令自己满意的网格布局。
基于之前提到的LinearLayout去模拟一个网格布局的实现思路,需要每一行都嵌套一个LinearLayout,通过weight去平分宽度。如果能把这个嵌套的LinearLayout去掉,就是我想要的效果了,于是我想到了GridLayout。
GridLayout是安卓的五大布局之一,但是用的比较少,最经典的案例就是做计算器的布局:
GridLayout最大的优势:可以设置在网格中的位置坐标,占用的格数。例如下面的xml:
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="300dp" android:layout_height="300dp" android:background="@color/colorPrimaryDark" app:alignmentMode="alignBounds" app:columnCount="3" app:horizontalSpacing="5dp" app:orientation="vertical" app:rowCount="3" app:verticalSpacing="5dp"> <TextView android:layout_width="100dp" android:layout_height="100dp" android:background="@color/colorAccent" app:layout_column="0" app:layout_row="0" /> <TextView android:layout_width="100dp" android:layout_height="100dp" android:background="@color/colorAccent" app:layout_column="1" app:layout_row="1" /> </android.support.v7.widget.GridLayout>
我们简单的复习了一下基本效果,接下来就可以动手实现了。
首先我们需要一个适配器,建议直接使用BaseAdapter,这样方便替换掉已经使用的GridView,而不用修改适配器的代码。
/** * 设置该控件的适配器 * */ var adapter: BaseAdapter? = null set(adapter) { // 解绑之前的adapter的数据监听 unregisterDataSetObserver() field = adapter this.count = field!!.count this.adapter!!.registerDataSetObserver(dataSetObserver) this.fillChildInLayout() } private val dataSetObserver = object : DataSetObserver() { override fun onChanged() { super.onChanged() count = adapter!!.count fillChildInLayout() } override fun onInvalidated() { super.onInvalidated() count = adapter!!.count fillChildInLayout() } }
设置了Adapter后,我们注册一个监听adapter数据的观察者,这样adapter.notifyDataSetChanged可以直接刷新内容的显示。
fillChildInLayout()是填充内容的方法:
/** * 通过adapter把item填入到GridLayout中 */ private fun fillChildInLayout() { if (adapter == null || count == 0) { clear() return } // 判断如果是竖向 if (orientation == GridLayout.VERTICAL) { fillChildInLayoutVertical() } else { fillChildInLayoutHorizontal() } // 如果当前child的数量比count要大,移除多余Child if (childCount > count) { removeViews(count, childCount - count) } }
首先判断adapter是否为空或者数量为0,我们只要删除所有的child就可以了。如果数量大于0,根据方向填充child,最后判断目前填充的child的个数和变化后的个数做对比,如果child个数多了,就都删掉。
每次刷新数据,频繁的移除和填充Child,实在是一种很笨的做法,不如更新已经填充的child,多退少补,优化性能。
下面以竖直方向的填充方法fillChildInLayoutVertical为例:
private fun fillChildInLayoutVertical() { val columnCount = columnCount // 遍历adapter for (position in 0 until count) { // 得到adapter中的View val child = getView(position) // 得到布局信息 val params = generateLayoutParams(child, position) // 设置水平方向的间距 if (position % columnCount == columnCount - 1) { params.rightMargin = 0 } else { params.rightMargin = horizontalSpace }// 中间的child // 设置竖直方向的间距, if (position > count - 1 - columnCount) { params.bottomMargin = 0 } else { params.bottomMargin = verticalSpace } // 设置点击之间 child.setOnClickListener { onCellClickListener?.onCellClick(position, this.adapter?.getItem(position) as T) } child.layoutParams = params if (child.parent == null) { addView(child) } } }
遍历adapter,得到指定位置的child,刷新child的显示,然后根据child所处的位置,设置右间距和下间距,最后一列不设置右间距,最后一行没有下间距,这样就实现了网格水平和上下的间距。
接下来看一下getView()方法,在这个方法中实现了之前提到的多退少补的优化策略:
/** * 从cache中得到View,没有则创建 */ private fun getView(index: Int): View { // 首先遍历已经存在的child,直接更新内容 // 这样可以节省清空再填充的性能浪费 var view: View? = null if (index < count) { view = getChildAt(index) } // 更新数据显示 view = this.adapter!!.getView(index, view, this) return view } class TestAdapter(private val context: Context, private val list: List<String>) : BaseAdapter() { override fun getItem(position: Int): String = list[position] override fun getItemId(position: Int): Long = position.toLong() override fun getCount(): Int = list.size override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { var view = convertView if(view == null){ view = LayoutInflater.from(context).inflate(R.layout.item_test, parent, false) } view!!.findViewById<TextView>(R.id.text).text = list[position] return view } }
首先查询是否已经添加了指定位置的child,然后调用adapter.getView(),如果没有找到child,会引入一个新的布局,如果找到了child,直接更新内容,这样已经添加的child直接得到了复用。
最后就是设置child的位置了:
/** * 生成LayoutParams */ private fun generateLayoutParams(child: View, position: Int): GridLayout.LayoutParams { val params: GridLayout.LayoutParams = if (child.layoutParams != null) { child.layoutParams as GridLayout.LayoutParams } else { GridLayout.LayoutParams() } // 设置宽度 if (orientation == VERTICAL) { // 设置所占的行数 params.columnSpec = GridLayout.spec(position % columnCount, 1, 1f) params.rowSpec = GridLayout.spec(position / columnCount, 1) } else { // 设置所占的行数 params.rowSpec = GridLayout.spec(position % rowCount, 1, 1f) params.columnSpec = GridLayout.spec(position / rowCount, 1) } return params }
GridLayout.LayoutParams简单的介绍一下:
columnSpec:child所在的列。
rowSpec:child所在的行。
GridLayout.spec(position % rowCount, 1, 1f)
第一个参数:所在列/行的位置;
第二个参数:所占用的个数,这里需要注意的是,格数仅仅是占用的数量,而不是宽度比;
第三个参数:所在的列/行,所占的宽度/高度的比例。
这就是GridLayoutView的全部实现,非常的简单,最后看一下实际的应用:
<!-- XML布局 -->
<com.lzp.grid.GridLayoutView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
app:columnCount="3"
app:horizontalSpacing="5dp"
app:orientation="vertical"
app:verticalSpacing="5dp" />
<!-- Java代码 -->
GridLayoutView<String> gridView = findViewById(R.id.grid);
gridView.setOnCellClickListener((index, s) -> Toast.makeText(this, s, Toast.LENGTH_SHORT).show());
gridView.setAdapter(adapter);
因为要在child的点击事件直接回调Adapter中的数据对象,所以需要指定Item的泛型。
这一次的内容相对来说比较简单,但是在思考的过程中发生了很多奇妙蛋疼的事情,最后给大家留下几个问题:
提示:计算宽高比,需要得到自身的宽度,如何解决getWidth/getHeight等于0的问题
需要了解View整体的添加和绘制流程,理解android的优化策略。
3、如果我们需要自定义LayoutParam,如何设置xml中添加的child的LayoutParam是自定义类型呢?
可以参考一下GridLayout源码
今天分享就这些了,如果有高手知道问题答案的话,欢迎留言大家共同学习,最后祝大家元旦愉快。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。