安卓RecycleView實現九宮格和點擊事件(詳解)

不久前做過一個App需要實現的功能比較多,因此打算做成一個九宮格的形式,把主要功能放到一個九宮格里來實現,這裏用到的是RecycleView。要求是每個子項的上方是功能圖標下方是功能名稱,並且給每一個子項實現一個不同的點擊事件,具體介紹如下。

一、效果圖

在這裏插入圖片描述

在這裏插入圖片描述

二、實現思路與代碼

2.1 添加依賴和控件

首先需要在項目的build.gradle添加相應的依賴庫,在dependencies閉包中添加如下內容。

 implementation 'com.android.support:recyclerview-v7:29.0.0'

其中29表示當前你所用SDK的版本號,注意使用時要與你當前的版本號一致。
然後在Activity中添加RecycleView控件。

  <!--核心功能-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_central"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ll_user"
        android:layout_centerInParent="true">

    </androidx.recyclerview.widget.RecyclerView>

2.2 定義主要功能類Central

由於我們這裏的每一個子項需要一張圖片和一段文字,因此在自定義Central類中定義兩個屬性值,其中Central_text對應功能名稱,Central_icon表示功能圖標對應的資源id,創建構造函數將屬性賦值,並用getter和setter進行封裝。

public class Central {
   
   
    String Central_text;
    int Central_icon;
    public Central(String central_text, int central_icon) {
   
   
        Central_text = central_text;
        Central_icon = central_icon;
    }
    public void setCentral_text(String central_text) {
   
   
        Central_text = central_text;
    }
    public void setCentral_icon(int central_icon) {
   
   
        Central_icon = central_icon;
    }
    public String getCentral_text() {
   
   
        return Central_text;
    }
    public int getCentral_icon() {
   
   
        return Central_icon;
    }
}

2.3 指定佈局central_item.xml

接下來需要給每一個子項指定自定義佈局,在layout目錄下新建佈局文件central_item.xml,代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:orientation="vertical"
        android:gravity="center_vertical"
        android:layout_marginLeft="10dp">
    <ImageView
        android:id="@+id/iv_central_icon"
        android:layout_width="55dp"
        android:layout_height="25dp"
        android:src="@drawable/helper_icon"/>
    <TextView
        android:id="@+id/tv_central_text"
        android:gravity="center"
        android:layout_width="55dp"
        android:layout_height="20dp"
        android:textSize="13sp"
        android:text="健康打卡"/>
    </LinearLayout>
</LinearLayout>

其中ImageView表示功能圖標,TextView表示功能名稱。

2.4 創建自定義適配器CentralAdapter

接下來也是實現的關鍵一步,新建CentralAdapter繼承自RecyclerView.Adapter,其中的泛型指定爲CentralAdapter.ViewHolder,ViewHolder是定義的一個內部類,用來獲取Image View、TextView的實例。這裏我貼上主要代碼。

public class CentralAdapter extends RecyclerView.Adapter<CentralAdapter.ViewHolder> {
   
   
    private  List<Central> mCentral;
    private Context context;


    public CentralAdapter(List<Central> mCentral,Context context) {
   
   
        this.mCentral = mCentral;
        this.context=context;
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
   
   
        View centralView;
        ImageView iv_central_icon;
        TextView tv_central_text;
        
        public ViewHolder(@NonNull View view) {
   
   
            super (view);
            centralView=view;
            iv_central_icon=view.findViewById (R.id.iv_central_icon);
            tv_central_text=view.findViewById (R.id.tv_central_text);
            ll_Background=view.findViewById (R.id.ll_background);
        }
    }
    @NonNull
    @Override
    public CentralAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
   
   
        View view= LayoutInflater.from (parent.getContext ()).
                inflate (R.layout.central_item,parent,false);
        ViewHolder holder=new ViewHolder (view);


        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull CentralAdapter.ViewHolder holder, final int position) {
   
   

        final Central central=mCentral.get (position);

        holder.iv_central_icon.setImageResource (central.getCentral_icon ());
        holder.tv_central_text.setText (central.getCentral_text ());
        holder.centralView.setOnClickListener (new View.OnClickListener () {
   
   
            @Override
            public void onClick(View view) {
   
   
               Intent intent=new Intent ();
                AlertDialog.Builder builder=new AlertDialog.Builder (context);
                builder.setTitle ("你點擊了");
                builder.setCancelable (true);

                switch (position){
   
   
                    //健康打卡
                    case 0:
                   /**
                      *這裏寫對應的點擊事件
                      */
                        break;
                    //個人軌跡
                    case 1:
                        break;
                    //澡堂預約
                    case 2:
                        break;
                    //風險等級
                    case 3:
                        break;
                    //請假申請
                    case 4:
                        break;
                    //危險區域
                    case 5:
                        break;
                    //領取綠碼
                    case 6:
                        break;
                    //防疫導航
                    case 7:
                        break;
                }
                  builder.setMessage (central.getCentral_text ());
                  builder.show ();
            }
        });
    }
    @Override
    public int getItemCount() {
   
   
        return mCentral.size ();
    }
}

代碼中onCreateViewHolder()方法是用來創建ViewHolder實例的,加載central_item佈局並通過構造函數將佈局傳入。onBindViewHolder()方法是用於對RecycleView子項的數據進行賦值(在子項被滾動到屏幕內時執行),通過position參數獲取當前項的實例,然後將數據設置到ViewHolder的ImageView和textView中。getItemCount()會告訴RecycleView有多少子項,返回數據的長度。

2.5 Activity中實現

2.5.1 定義全局變量

    public List<Central> centralList = new ArrayList<> ();
    RecyclerView recyclerView;

2.5.2 初始化Central類集合

這一步利用構造函數將每一個Central初始化並添加到Central集合中,我把他寫在了一個函數方法中,需要在onCreate()方法中調用

  /**
     *初始化核心功能數組
     */
    private void initCentral() {
   
   
        Central central_clock = new Central (getString (R.string.central_health_clock), R.mipmap.central_health_clock);
        centralList.add (central_clock);
        Central central_trail = new Central (getString (R.string.central_trail_mine), R.mipmap.central_trail_mine);
        centralList.add (central_trail);
        Central central_bath = new Central (getString (R.string.central_bespeak_bath), R.mipmap.central_bespeak_bath);
        centralList.add (central_bath);
        Central central_levelMap1 = new Central (getString (R.string.central_level_map),R.mipmap.central_level_map);
        centralList.add (central_levelMap1);
        Central central_out = new Central (getString (R.string.central_bespeak_out), R.mipmap.central_bespeak_out);
        centralList.add (central_out);
        Central central_danger = new Central (getString (R.string.central_area_danger), R.mipmap.central_area_danger);
        centralList.add (central_danger);
        Central central_qr = new Central (getString (R.string.central_health_qr), R.mipmap.central_health_qr);
        centralList.add (central_qr);
        Central central_navigation=new Central (getString (R.string.central_navigation_pre),R.mipmap.central_navigation_pre);
        centralList.add (central_navigation);

    }

2.5.3 RecycleView適配

這裏總共有八個功能,要求將八個功能分成兩行展示,這一步在初始化數組之後執行,實現代碼如下。


        recyclerView = ((RecyclerView) findViewById (R.id.rv_central));
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager
                (2, StaggeredGridLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager (layoutManager);
        CentralAdapter centralAdapter = new CentralAdapter (centralList, getContext ());
        recyclerView.setAdapter (centralAdapter);

    }

其中創建了一個StaggeredGridLayoutManager的實例,通過構造函數傳入了兩個參數,第一個參數用於指定佈局的列數,第二個參數用於指定佈局的排列方向。這裏我指定了列數爲兩列,橫向排列。如果要實現3x3的排列,將第一個參數改成3即可。
到這裏就完成了。

三、結語

對於以上大家有什麼問題歡迎評論指正!如果有需要,後續我會上傳源代碼。
另外隨着編程量的增加,代碼的規範性和可讀性逐漸提升了,後續可能會對之前發佈的博客進行一次更新,另外Java的基礎鞏固以及進階學習要儘早提上日程,後面也會發布相關的博客。加油,代碼人!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章