Android RecyclerView实现九宫格效果


Posted in Java/Android onJune 28, 2022

RecyclerView更加优化的复用机制和方便实现UI效果,几乎替代Listview和GridView的使用。但是分割线的实现,需要自己继承ItemDecoration来绘制。

效果图

Android RecyclerView实现九宫格效果

item的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="餐饮"
            android:id="@+id/txt_title"
            android:textSize="16sp"
            android:textStyle="bold"
            android:textColor="#555555"/>

        <ImageView
            android:layout_width="36dp"
            android:layout_height="36dp"
            android:id="@+id/img_title"
            android:src="@mipmap/luggage_blue"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:orientation="vertical"
        android:layout_marginBottom="25dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="提供航空 餐饮美食"
            android:id="@+id/txt_info"
            android:textSize="14sp"
            android:textColor="#999999"/>
    </LinearLayout>

</LinearLayout>

activity_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f1f1f1"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textColor="#ffffff"
        android:textSize="18sp"
        android:gravity="center"
        android:text="RecyclerView实现九宫格"
        android:background="#30B8E3"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:gravity="center_vertical"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:orientation="horizontal">

                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:src="@mipmap/air_gray"
                    android:layout_marginRight="8dp"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="航行助手"
                    android:textStyle="bold"
                    android:textSize="18sp"/>
            </LinearLayout>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/main_recycleview"
                android:divider="#00000000"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/shape_bg"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp">
            </android.support.v7.widget.RecyclerView>

        </LinearLayout>
    </ScrollView>

</LinearLayout>

MainActivity.java代码

package com.davis.recyclerviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.davis.recyclerviewdemo.adapter.CommonDecoration;
import com.davis.recyclerviewdemo.adapter.RecyclerViewAdapter;
import com.davis.recyclerviewdemo.bean.MenuBean;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;
    private List<MenuBean> listDatas = new ArrayList<MenuBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init(){
        recyclerView = (RecyclerView)findViewById(R.id.main_recycleview);
        loadMenuData();

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.addItemDecoration(new CommonDecoration(this));

        adapter = new RecyclerViewAdapter(this, listDatas);
        recyclerView.setAdapter(adapter);
    }

    private void loadMenuData(){
        listDatas.add(new MenuBean("安检", "快速安检", R.mipmap.check_blue));
        listDatas.add(new MenuBean("行李", "提醒行李动态", R.mipmap.luggage_blue));
        listDatas.add(new MenuBean("餐饮", "提供航空 餐饮美食", R.mipmap.food_blue));
        listDatas.add(new MenuBean("VIP休息", "机场休息室", R.mipmap.vip_blue));
        listDatas.add(new MenuBean("机舱服务", "机舱上网 游戏娱乐", R.mipmap.service_blue));
        listDatas.add(new MenuBean("更多", "更多信息", R.mipmap.more_blue));
    }
}

其中GridLayoutManager用来设置显示列数,CommonDecoration用来绘制分隔线。

CommonDecoration.java代码

package com.davis.recyclerviewdemo.adapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

/**
 * Created by Administrator on 2019/4/14.
 */

public class CommonDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable mDivider;

    public CommonDecoration(Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

        drawHorizontal(c, parent);
        drawVertical(c, parent);

    }

    private int getSpanCount(RecyclerView parent) {
        // 列数
        int spanCount = -1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {

            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getLeft() - params.leftMargin;
            final int right = child.getRight() + params.rightMargin
                    + mDivider.getIntrinsicWidth();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getTop() - params.topMargin;
            final int bottom = child.getBottom() + params.bottomMargin;
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
                                int childCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            // 如果是最后一列,则不需要绘制右边
            if ((pos + 1) % spanCount == 0) {
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                // 如果是最后一列,则不需要绘制右边
                if ((pos + 1) % spanCount == 0) {
                    return true;
                }
            } else {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount) {// 如果是最后一列,则不需要绘制右边
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            int last = childCount % spanCount;
            if (last == 0) {
                last = spanCount;
            }
            childCount = childCount - last;
            if (pos >= childCount) {// 如果是最后一行,则不需要绘制底部
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            // StaggeredGridLayoutManager 且纵向滚动
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                int last = childCount % spanCount;
                if (last == 0) {
                    last = spanCount;
                }
                childCount = childCount - last;
                // 如果是最后一行,则不需要绘制底部
                if (pos >= childCount) {
                    return true;
                }
            } else {// StaggeredGridLayoutManager 且横向滚动
                // 如果是最后一行,则不需要绘制底部
                if ((pos + 1) % spanCount == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent) {
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();

        if (isLastColum(parent, itemPosition, spanCount, childCount)) {// 如果是最后一列,则不需要绘制右边
            if (itemPosition == (childCount - 1)) {
                outRect.set(0, 0, 0, 0);
            } else {
                outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
            }
        } else if (isLastRaw(parent, itemPosition, spanCount, childCount)) {// 如果是最后一行,则不需要绘制底部
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                    mDivider.getIntrinsicHeight());
        }
    }
}

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


Tags in this post...

Java/Android 相关文章推荐
详解SpringBoot异常处理流程及原理
Jun 21 Java/Android
SpringBoot实现异步事件驱动的方法
Jun 28 Java/Android
分析JVM源码之Thread.interrupt系统级别线程打断
Jun 29 Java/Android
Spring实现内置监听器
Jul 09 Java/Android
用Java实现简单计算器功能
Jul 21 Java/Android
java泛型通配符详解
Jul 25 Java/Android
一篇文章带你学习Mybatis-Plus(新手入门)
Aug 02 Java/Android
Java 获取Word中所有的插入和删除修订的方法
Apr 06 Java/Android
Java 异步任务计算FutureTask
Apr 28 Java/Android
Spring Security动态权限的实现方法详解
Jun 16 Java/Android
springboot集成redis存对象乱码的问题及解决
Jun 16 Java/Android
Java服务调用RestTemplate与HttpClient的使用详解
Jun 21 Java/Android
Java 多线程并发FutureTask
Java+swing实现抖音上的表白程序详解
Jun 25 #Java/Android
Java Spring Boot请求方式与请求映射过程分析
Jun 25 #Java/Android
Spring Cloud OAuth2实现自定义token返回格式
Jun 25 #Java/Android
Spring Cloud OpenFeign模版化客户端
Jun 25 #Java/Android
Java服务调用RestTemplate与HttpClient的使用详解
Jun 21 #Java/Android
springboot创建的web项目整合Quartz框架的项目实践
Jun 21 #Java/Android
You might like
php下将图片以二进制存入mysql数据库中并显示的实现代码
2010/05/27 PHP
设置php页面编码的两种方法示例介绍
2014/03/03 PHP
谈谈你对Zend SAPIs(Zend SAPI Internals)的理解
2015/11/10 PHP
当鼠标移动到图片上时跟随鼠标显示放大的图片效果
2013/06/06 Javascript
js数组依据下标删除元素
2015/04/14 Javascript
jQuery EasyUI 布局之动态添加tabs标签页
2015/11/18 Javascript
JavaScript学习笔记之数组随机排序
2016/03/23 Javascript
学习Angularjs分页指令
2016/07/01 Javascript
js智能获取浏览器版本UA信息的方法
2016/08/08 Javascript
JSON对象 详解及实例代码
2016/10/18 Javascript
js实现华丽的九九乘法表效果
2017/03/29 Javascript
VueAwesomeSwiper在VUE中的使用以及遇到的一些问题
2018/01/11 Javascript
Vue.js+Layer表格数据绑定与实现更新的实例
2018/03/07 Javascript
浅谈node中的cluster集群
2018/06/02 Javascript
浅谈关于vue中scss公用的解决方案
2019/12/02 Javascript
python中将阿拉伯数字转换成中文的实现代码
2011/05/19 Python
python通过scapy获取局域网所有主机mac地址示例
2014/05/04 Python
Python模拟三级菜单效果
2017/09/11 Python
Python 用Redis简单实现分布式爬虫的方法
2017/11/23 Python
Python+树莓派+YOLO打造一款人工智能照相机
2018/01/02 Python
详解tensorflow训练自己的数据集实现CNN图像分类
2018/02/07 Python
Python实现矩阵相乘的三种方法小结
2018/07/26 Python
Python django使用多进程连接mysql错误的解决方法
2018/10/08 Python
python模块之subprocess模块级方法的使用
2019/03/26 Python
Python基于class()实现面向对象原理详解
2020/03/26 Python
小结Python的反射机制
2020/09/28 Python
存储过程的优点有哪些
2012/09/27 面试题
医科大学生毕业的自我评价分享
2013/11/12 职场文书
产品质量承诺书范文
2014/03/27 职场文书
春节请假条
2014/04/11 职场文书
交通事故私了协议书
2014/04/16 职场文书
捐献物资倡议书范文
2014/05/19 职场文书
个人三严三实对照检查材料思想汇报
2014/09/22 职场文书
酒店客房服务员岗位职责
2015/04/09 职场文书
2015年计算机教学工作总结
2015/07/22 职场文书
JavaScript数组reduce()方法的语法与实例解析
2021/07/07 Javascript