Computer >> Máy Tính >  >> Lập trình >> Android

Ví dụ về lưới Android đơn giản bằng cách sử dụng RecyclerView với GridLayoutManager

Trước khi đi vào trình quản lý bố cục lưới cho ví dụ về chế độ xem tái chế, chúng ta nên biết chế độ xem Recycler trong Android là gì. Chế độ xem trình tái chế là phiên bản nâng cao hơn của chế độ xem danh sách và nó hoạt động dựa trên mẫu thiết kế ngăn chứa Chế độ xem. Sử dụng chế độ xem tái chế, chúng tôi có thể hiển thị lưới và danh sách các mục.

Ví dụ này minh họa về cách tích hợp Recycler View với trình quản lý bố cục Grid bằng cách tạo một ứng dụng hồ sơ học sinh đẹp mắt hiển thị tên học sinh theo tuổi.

Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Mở build.gradle và thêm phụ thuộc vào thư viện chế độ xem Recycler.

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.tutorialspoint"
      minSdkVersion 19
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support:design:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   implementation 'com.android.support:recyclerview-v7:28.0.0'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Bước 3 - Thêm mã sau vào res / layout / activity_main.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:tools = "https://schemas.android.com/tools"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   app:layout_behavior = "@string/appbar_scrolling_view_behavior"
   tools:showIn = "@layout/activity_main"
   tools:context = ".MainActivity">
   <android.support.v7.widget.RecyclerView
      android:id = "@+id/recycler_view"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:scrollbars = "vertical" />
</RelativeLayout>

Trong đoạn mã trên, chúng tôi đã thêm chế độ xem trình tái chế vào trình quản lý cửa sổ dưới dạng bố cục mẹ tương đối.

Bước 4 - Thêm mã sau vào src / MainActivity.java

package com.example.andy.tutorialspoint;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class MainActivity extends AppCompatActivity {
   private RecyclerView recyclerView;
   private StudentAdapter studentAdapter;
   private List studentDataList = new ArrayList<>();
   @TargetApi(Build.VERSION_CODES.O)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      recyclerView = findViewById(R.id.recycler_view);
      studentAdapter = new StudentAdapter(studentDataList);
      RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);
      recyclerView.setLayoutManager(manager);
      recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
      recyclerView.setAdapter(studentAdapter);
      StudentDataPrepare();
   }
   @RequiresApi(api = Build.VERSION_CODES.N)
   private void StudentDataPrepare() {
      studentData data = new studentData("sai", 25);
      studentDataList.add(data);
      data = new studentData("sai", 25);
      studentDataList.add(data);
      data = new studentData("raghu", 20);
      studentDataList.add(data);
      data = new studentData("raj", 28);
      studentDataList.add(data);
      data = new studentData("amar", 15);
      studentDataList.add(data);
      data = new studentData("bapu", 19);
      studentDataList.add(data);
      data = new studentData("chandra", 52);
      studentDataList.add(data);
      data = new studentData("deraj", 30);
      studentDataList.add(data);
      data = new studentData("eshanth", 28);
      studentDataList.add(data);
      Collections.sort(studentDataList, new Comparator() {
         @Override
         public int compare(studentData o1, studentData o2) {
            return o1.name.compareTo(o2.name);
         }
      });
   }
}

Trong đoạn mã trên, chúng tôi đã thêm chế độ xem trình tái chế và studentAdapter. Trong bộ điều hợp sinh viên đó, chúng tôi đã chuyển studentDatalist làm danh sách mảng. Trong danh sách dữ liệu Sinh viên có tên của sinh viên và tuổi.

Để có được lưới, chúng ta phải sử dụng trình quản lý bố cục lưới như hình dưới đây -

RecyclerView.LayoutManager manager = new GridLayoutManager(this, 2);

Trong đoạn mã trên, chúng tôi đã sử dụng trình quản lý bố cục là GridlayoutManger và thêm các ô làm 2. Vì vậy, nó sẽ hiển thị kết quả với hai lưới trong mỗi hàng.

Để so sánh các mục trong chế độ xem tái chế, chúng tôi đã sử dụng khung bộ sưu tập và phương pháp sắp xếp như được hiển thị bên dưới -

Collections.sort(studentDataList, new Comparator() {
   @Override
   public int compare(studentData o1, studentData o2) {
      return o1.name.compareTo(o2.name);
   }
});

Trong đoạn mã trên, chúng tôi đang so sánh các phần tử bằng cách sử dụng tên.

Bước 5 - Sau đây là nội dung của tệp đã sửa đổi src / StudentAdapter.java.

package com.example.andy.tutorialspoint;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;
import java.util.Random;

class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
   List<studentData> studentDataList;
   public StudentAdapter(List<studentData> studentDataList) {
      this.studentDataList = studentDataList;
   }
   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
      View itemView = LayoutInflater.from(viewGroup.getContext())
      .inflate(R.layout.student_list_row, viewGroup, false);
      return new MyViewHolder(itemView);
   }
   @Override
   public void onBindViewHolder(MyViewHolder viewHolder, int i) {
      studentData data=studentDataList.get(i);
      Random rnd = new Random();
      int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
      viewHolder.parent.setBackgroundColor(currentColor);
      viewHolder.name.setText(data.name);
      viewHolder.age.setText(String.valueOf(data.age));
   }
   @Override
   public int getItemCount() {
      return studentDataList.size();
   }
   class MyViewHolder extends RecyclerView.ViewHolder {
      TextView name,age;
      LinearLayout parent;
      public MyViewHolder(View itemView) {
         super(itemView);
         parent = itemView.findViewById(R.id.parent);
         name = itemView.findViewById(R.id.name);
         age = itemView.findViewById(R.id.age);
      }
   }
}

Trong lớp bộ điều hợp, chúng tôi có bốn phương thức như được hiển thị bên dưới -

  • onCreateViewHolder () :- Nó được sử dụng để tạo khung giữ khung nhìn và nó trả về một khung nhìn.

  • onBindViewHolder () - nó sẽ liên kết với trình giữ chế độ xem đã tạo.

  • getItemCount () - nó chứa kích thước của danh sách.

  • Lớp MyViewHolder - đó là lớp bên trong của người giữ chế độ xem được mở rộng bởi RecyclerView.ViewHolder

Để đặt nền ngẫu nhiên cho các mục trong chế độ xem tái chế, chúng tôi đã tạo các màu ngẫu nhiên bằng cách sử dụng lớp ngẫu nhiên (là lớp được xác định trước trong Android) và thêm màu vào mục gốc của chế độ xem như được hiển thị bên dưới -

Random rnd = new Random();
int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
viewHolder.parent.setBackgroundColor(currentColor);

Bước 6 - Sau đây là nội dung sửa đổi của xml res / layout / student_list_row.xml.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   android:orientation = "horizontal" android:layout_width="match_parent"
   android:weightSum =" 1"
   android:layout_height="wrap_content">
   <TextView
      android:id = "@+id/name"
      android:layout_width = "0dp"
      android:layout_weight = "0.5"
      android:gravity = "center"
      android:textSize = "15sp"
      android:layout_height = "100dp" />
      <TextView
      android:id = "@+id/age"
      android:layout_width = "0dp"
      android:layout_weight = "0.5"
      android:gravity = "center"
      android:textSize = "15sp"
      android:layout_height = "100dp" />
</LinearLayout>

Trong chế độ xem danh sách ở trên, chúng tôi đã tạo hai chế độ xem văn bản cho tên và tuổi.

Bước 7 - Sau đây là nội dung của tệp đã sửa đổi src / studentData.java.

package com.example.andy.tutorialspoint;

class studentData {
   String name;
   int age;
   public studentData(String name, int age) {
      this.name = name;
      this.age = age;
   }
}

Ở trên thông báo về đối tượng dữ liệu sinh viên. Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn -

Ví dụ về lưới Android đơn giản bằng cách sử dụng RecyclerView với GridLayoutManager