本文主要是介绍GridView设置分割线与dispatchDraw,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自定义GridView :
在dispatchDraw中绘制分割线。
public class MyDividerGridView extends GridView {private Paint paint;public MyDividerGridView(Context context) {super(context);initPaint();}public MyDividerGridView(Context context, AttributeSet attrs) {super(context, attrs);initPaint();}public MyDividerGridView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);initPaint();}private void initPaint() {paint = new Paint();paint.setStyle(Paint.Style.STROKE);paint.setColor(Color.parseColor("#e6e6e6"));}@Overrideprotected void dispatchDraw(Canvas canvas) {super.dispatchDraw(canvas);//子view的总数int childTotalCount = getChildCount();//列数int columnCount = getNumColumns();//行数int rowCount;if (childTotalCount % columnCount == 0) {rowCount = childTotalCount / columnCount;} else {rowCount = (childTotalCount / columnCount) + 1; //当余数不为0时,要把结果加上1}for (int i = 0; i < childTotalCount; i++) {//遍历子viewView cellView = getChildAt(i);//获取子viewint height = cellView.getHeight();//子view的高度if (!(i % columnCount == 0)) {//不是第一列canvas.drawLine(cellView.getLeft(), cellView.getTop() + 0.15f * height,cellView.getLeft(), cellView.getBottom() - 0.15f * height, paint);}if (!(i >= (rowCount - 1) * columnCount)) {//不是最后一行的第一个及其他canvas.drawLine(cellView.getLeft(), cellView.getBottom(),cellView.getRight(), cellView.getBottom(), paint);}}}
}
布局中使用:
<com.dch.dai.view.MyDividerGridViewandroid:id="@+id/help_gv"android:layout_width="match_parent"android:layout_height="wrap_content"android:horizontalSpacing="0.0dip"android:listSelector="@null"android:background="@color/white"android:numColumns="3"android:scrollbars="none"android:stretchMode="columnWidth"android:verticalSpacing="0.0dip" />
效果:
其他:
去除默认selector:
1、gridview的布局中:
android:listSelector="@null"
2、在item布局的根布局添加background的selector即可:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/help_gv_item_container"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="?android:attr/selectableItemBackground"android:orientation="vertical"><ImageViewandroid:id="@+id/help_gv_item_iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_marginTop="28dp"android:src="@drawable/reglogin" /><TextViewandroid:id="@+id/help_gv_item_tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/help_gv_item_iv"android:layout_centerHorizontal="true"android:layout_weight="1"android:gravity="center_horizontal"android:paddingBottom="17dp"android:paddingTop="12dp"android:text="登录/注册"android:textColor="#666666"android:textSize="13sp" /></RelativeLayout>
这篇关于GridView设置分割线与dispatchDraw的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!