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 相关文章推荐
浅析NIO系列之TCP
Jun 15 Java/Android
Spring Boot两种全局配置和两种注解的操作方法
Jun 29 Java/Android
mybatis中sql语句CDATA标签的用法说明
Jun 30 Java/Android
Java实现聊天机器人完善版
Jul 04 Java/Android
mybatis3中@SelectProvider传递参数方式
Aug 04 Java/Android
Spring Data JPA框架持久化存储数据到数据库
Apr 28 Java/Android
Java 多线程协作作业之信号同步
May 11 Java/Android
SpringBoot全局异常处理方案分享
May 25 Java/Android
openGauss数据库JDBC环境连接配置的详细过程(Eclipse)
Jun 01 Java/Android
Java实现带图形界面的聊天程序
Jun 10 Java/Android
Java实现HTML转为Word的示例代码
Jun 28 Java/Android
Java多线程并发FutureTask使用详解
Jun 28 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
一个MYSQL操作类
2006/11/16 PHP
PHP CURL 内存泄露问题解决方法
2015/02/12 PHP
基于laravel制作APP接口(API)
2016/03/15 PHP
PHP微信开发之模板消息回复
2016/06/24 PHP
PHP实现动态添加XML中数据的方法
2018/03/30 PHP
Laravel如何自定义command命令浅析
2019/03/23 PHP
关于javascript 回调函数中变量作用域的讨论
2009/09/11 Javascript
JQuery扩展插件Validate—4设置错误提示的样式
2011/09/05 Javascript
javascript实现锁定网页、密码解锁效果(类似系统屏幕保护效果)
2014/08/15 Javascript
原生js实现日期联动
2015/01/12 Javascript
jQuery使用$.ajax进行即时验证的方法
2015/12/08 Javascript
Javascript的无new构建实例详解
2016/05/15 Javascript
JS实现将数字金额转换为大写人民币汉字的方法
2016/08/02 Javascript
AngularGauge 属性解析详解
2016/09/06 Javascript
使用express获取微信小程序二维码小记
2019/05/21 Javascript
python脚本实现xls(xlsx)转成csv
2016/04/10 Python
Python yield 使用方法浅析
2017/05/20 Python
Django框架的使用教程路由请求响应的方法
2018/07/03 Python
Python可视化mhd格式和raw格式的医学图像并保存的方法
2019/01/24 Python
python中使用while循环的实例
2019/08/05 Python
python 多进程共享全局变量之Manager()详解
2019/08/15 Python
Python Numpy中数据的常用保存与读取方法
2020/04/01 Python
如何基于线程池提升request模块效率
2020/04/18 Python
python 基于UDP协议套接字通信的实现
2021/01/22 Python
5分钟让你掌握css3阴影、倒影、渐变小技巧(小编推荐)
2016/08/15 HTML / CSS
html5 canvas-1.canvas介绍(hello canvas)
2013/01/07 HTML / CSS
2014年应届大学生毕业自我鉴定
2014/01/31 职场文书
执行总经理岗位职责
2014/02/03 职场文书
战略合作协议书范本
2014/04/18 职场文书
党的群众路线教育实践活动个人整改方案
2014/10/25 职场文书
中学生思想品德评语
2014/12/31 职场文书
老龙头导游词
2015/02/11 职场文书
大学四年个人总结
2015/03/03 职场文书
超级实用!五步法则,教你写好年终工作总结
2019/12/05 职场文书
聊聊golang中多个defer的执行顺序
2021/05/08 Golang
MySQL数据库优化之通过索引解决SQL性能问题
2022/04/10 MySQL