GridView相关

2018-01-23  本文已影响29人  鲁西西z

这两天项目正好用到GridView,在此记录这次使用GridView所遇到的问题,虽然问题都很小白。

1、GridView均分问题

<com.jsepc.omspf.platform.WIDGET.GridViewSplitLine 
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchMode="columnWidth"  <!-- 剩余空间均分到每列 -->
    android:background="#ffffff"
    android:numColumns="3"
    android:columnWidth="100dp"
    android:gravity="center"
    android:listSelector="#FFFFFF"
    />

android:stretchMode属性:决定怎么分配剩余空间

2、自定义带分割线的GridView

public class GridViewSplitLine extends GridView 

// 定义行数
private int rowNum;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 获取列数
    int column = getNumColumns();
    // 获取item总数
    int total = getChildCount();
    
    // 计算行数
    if(total % column == 0){
        rowNum = total/column;
    }else{
        rowNum = total/column+1;
    }
    
    // 设置画笔
    Paint paint = new Paint();
    paint.setColor(Color.parseColor("#D8D8D8"));
    paint.setStrokeWidth(5);
    paint.setStyle(Style.STROKE);
    
    // 第一列最后一个item
    View viewRowLast = getChildAt((rowNum-1)*column);
    
    int width = getWidth();
    int height = viewRowLast.getBottom();
    
    // 绘制横线
    for (int i = 0; i < rowNum; i++) {
        View v = getChildAt(i*column);
        canvas.drawLine(0, v.getBottom(), width, v.getBottom(), paint);
    }
    
    // 绘制竖线
    for (int i = 0; i < column-1; i++) {
        View v = getChildAt(i);
        canvas.drawLine(v.getRight(), 0, v.getRight(), height, paint);
    }
}
分割线GridView效果图

因项目最后一行正好排满,就没有考虑最后一行不足三项的情况,如果有这个需要,大家可以在循环时加个判断。

上一篇 下一篇

猜你喜欢

热点阅读