Android RecyclerView实现九宫格效果

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

完整代码已上传至Github: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"><LinearLayoutandroid: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"><TextViewandroid: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"/><ImageViewandroid:layout_width="36dp"android:layout_height="36dp"android:id="@+id/img_title"android:src="@mipmap/luggage_blue"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="20dp"android:orientation="vertical"android:layout_marginBottom="25dp"android:layout_marginLeft="15dp"android:layout_marginRight="15dp"><TextViewandroid: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"><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:textColor="#ffffff"android:textSize="18sp"android:gravity="center"android:text="RecyclerView实现九宫格"android:background="#30B8E3"/><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:gravity="center_vertical"android:layout_marginLeft="15dp"android:layout_marginRight="15dp"android:orientation="horizontal"><ImageViewandroid:layout_width="20dp"android:layout_height="20dp"android:src="@mipmap/air_gray"android:layout_marginRight="8dp"/><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="航行助手"android:textStyle="bold"android:textSize="18sp"/></LinearLayout><android.support.v7.widget.RecyclerViewandroid: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>();@Overrideprotected 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();}@Overridepublic 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;}@Overridepublic 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());}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/446807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何读取指针指向的地址空间呢?

方法 使用%p 接收指针返回的地址空间 代码 #include <stdio.h> #include <stdlib.h>int main() {int a 100;int *a_p &a;printf("%p\n",&a);//输出&#xff1a;002AF744 输出的是a变量的地址printf("%p\n",a_p);//输出&#xff1…

科学究研明表,汉字序顺并不一定影阅响读

有个很有意思的现象&#xff1a; 不信你就来试试 中文打乱小工具 github地址&#xff1a;在线打乱文字顺序

安卓EditText

常用属性 android:textAllCaps"false"去除大写状态 inputType 常用 textpassword密码 number数字 phone拨号键盘 设置光标位置 editText.setSelection(2);从1开始 editText.setSelection(1,3);从1开始,1–3中间部分,一个范围

完善博文 共享内存一写多读无锁实现的代码逻辑部分

使用共享内存(内存映射)实现发布订阅模式 多进程实现PubSub发布订阅模式&#xff0c;从而实现进程间的通信。通信方式可以是TCP/UDP&#xff0c;管道Pipe/消息队列&#xff0c;共享内存shared memory等等。其中TCP/UDP的方式是可以用作局域网以及跨平台的通信&#xff0c;Pipe…

想对你说的话,就在这里!

甜(Tu)言(Wei)蜜(Qing)语(Hua)最近在github上看到了一个朋友开发的 土味情话在线生成器 &#xff0c;感觉还不错&#xff0c;在这里推荐一下。 github地址&#xff1a;在线生成土味情话

linux读写文件 简单版

代码 //write void write_file(const std::string file_name){FILE *fp nullptr;fp fopen(file_name.c_str(),"w");fprintf(fp,"This is testing for mutex\n");fclose(fp); } //read void read_file(const std::string file_name){std::ifstream fp(fi…

具有中国风的传统颜色(炫酷)

一个小小的中国风的传统颜色&#xff0c;你觉得应该是什么样子的呢&#xff1f; 看了下面这个&#xff0c;我一个搞移动开发的都想去搞前端开发了。 废话不多说了&#xff0c;直接看效果&#xff1a; 访问地址&#xff1a;中国传统颜色手册 github地址&#xff1a;Chinese…

Android Studio安装问题及填坑

安装过程 安装Android Studio 其他问题 1.Android Studio出现Error:Unable to tunnel through proxy. Proxy returns “HTTP/1.1 400 Bad Request” 2.Could not resolve all artifacts for configuration :classpath 3.!No cached version of com.android.tools.build:gr…

Linux strtol将十六进制转化为十进制

代码 #include <iostream> #include "crypto_util.h"int get_file(const std::string file_name){size_t get_file_id 0;std::cout << hsm::common::get_md5_digest_hex(file_name) << std::endl;get_file_id strtol(reinterpret_cast<const…

Android WebView使用攻略

目录前言一、简介二、作用三、使用介绍1、Webview类常用方法1.1、加载url1.2、WebView的状态1.3、关于前进 / 后退网页1.4、清除缓存数据2、常用工具类2.1、WebSettings类2.2、WebViewClient类2.3、WebChromeClient类3、注意事项&#xff1a;如何避免WebView内存泄露&#xff1…

C++If与Switch语句

IF if语句不加括号就只是一个语句 举例: int a5,b2; if(a)//按逻辑值来理解,0为假,其他为真,这里等价于a!0—>a为真时 ab; else ba; 计算三角形面积代码 #include<iostream> #include<cmath>//数学公式库 #include<iomanip> //格式控制 using namesp…

linux fork多进程 demo

注释 使用系统调用fork()创建三个子进程&#xff1b;各个子进程显示和输出一些提示信息和自己的进程标识符&#xff1b;父进程显示自己的进程ID和一些提示信息&#xff0c;然后调用waitpid()等待多个子进程结束&#xff0c;并在子进程结束后显示输出提示信息表示程序结束。 代…

Android WebView 与 JS 交互

目录二、具体分析2.1 Android通过WebView调用 JS 代码方式1&#xff1a;通过WebView的loadUrl()方式2&#xff1a;通过WebView的evaluateJavascript()方法对比使用建议2.2、JS通过WebView调用 Android 代码2.2.1、方法分析方式1&#xff1a;通过 WebView的addJavascriptInterfa…

关于锁的注意事项

文件锁 Linux 提供了 fcntl 系统调用&#xff0c;可以锁定文件但是文件锁是和进程相关联的&#xff0c;一个进程中的多个线程/协程对同一个文件进行的锁操作会互相覆盖掉&#xff0c;从而无效。fcntl 创建的锁是建议性锁&#xff0c;只有写入的进程和读取的进程都遵循建议才有效…

安卓实现登录与注册界面

使用Intent与Bundle传递数据 登录界面login.xml 1.使用Relativelayout相对布局 <?xml version"1.0" encoding"utf-8"?> <RelativeLayout xmlns:android"http://schemas.android.com/apk/res/android"android:layout_width"mat…

Android Button字母自动全部大写的问题

两种解决方案&#xff1a; 方法一&#xff1a; 在 xml 布局中设置属性 android:textAllCaps"false" <Buttonandroid:layout_width"wrap_content"android:layout_height"match_parent"android:text"添加动作组"android:textAllCap…

安卓Activity与intent跳转

Activity生命周期 Activity启动模式 Intent跳转 _________startActivity() 1.Intent intentnew Intent(A.this,B.class); startActivity(intent); 2.startActivity(new Intent(A.this,B.class)); _________startActivityForResult() Intent intentnew Intent(A.this,B.class…

将读写锁放到共享内存中,实现进程之间对数据的读写访问控制

代码 #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <assert.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <…

Android WebView 使用漏洞

目录一、类型二、具体分析2.1、WebView任意代码执行漏洞2.1.1、addJavascriptInterface 接口引起远程代码执行漏洞漏洞产生原因解决方案关于该方法的其他细节总结2.1.2、searchBoxJavaBridge_接口引起远程代码执行漏洞漏洞产生原因解决方案2.1.3、accessibility和 accessibilit…

将读写锁放到共享内存,实现进程之间对于同一文件的读写操作

思路 将读写锁和读写锁的属性以及一个用于存储共享内存的地址的int型变量三者封装成一个struct结构将这个结构体放到共享内存中&#xff0c;以及将读写锁的属性设置成全局性质&#xff0c;然后使用这个属性初始化锁&#xff0c;以及将锁的地址关联到结构体的内存地址这个变量定…