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.pswp.cn/news/446807.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/446807.shtml
英文地址,請注明出處:http://en.pswp.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;以及將鎖的地址關聯到結構體的內存地址這個變量定…