Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

Android에서 RecyclerView 어댑터 데이터를 업데이트하는 방법은 무엇입니까?

<시간/>

예제를 시작하기 전에 Android에서 Recycler 보기가 무엇인지 알아야 합니다. Recycler 보기는 목록 보기의 고급 버전이며 보기 홀더 디자인 패턴을 기반으로 작동합니다. 리사이클러 보기를 사용하여 그리드와 항목 목록을 표시할 수 있습니다.

이 예는 나이와 함께 학생 이름을 표시하는 아름다운 학생 기록 앱을 만들어 Recycler View 어댑터를 업데이트하는 방법을 보여줍니다.

1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 − build.gradle을 열고 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:cardview-v7:28.0.0'
   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'
}

3단계 − 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:layout_marginBottom = "50dp"
      android:scrollbars = "vertical" />
   <LinearLayout
      android:layout_width = "match_parent"
      android:layout_below = "@+id/recycler_view"
      android:layout_marginTop = "-50dp"
      android:layout_alignParentBottom = "true"
      android:layout_height = "wrap_content">
      <Button
         android:id = "@+id/add"
         android:layout_width = "wrap_content"
         android:layout_height = "wrap_content"
         android:text = "add item"/>
      <Button
         android:id = "@+id/remove"
         android:layout_width = "wrap_content"
         android:text = "remove item"
         android:layout_height = "wrap_content" />
   </LinearLayout>
</RelativeLayout>

위의 코드에서 창 관리자에 상대적인 부모 레이아웃으로 리사이클러 보기를 추가하고 추가 및 제거로 두 개의 버튼을 추가했습니다. 추가 버튼은 리사이클러뷰 어댑터에 데이터를 추가하고 제거 버튼은 리사이클러뷰에서 데이터를 제거합니다.

4단계 − 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 android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

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);
      Button add = findViewById(R.id.add);
      Button remove = findViewById(R.id.remove);
      recyclerView = findViewById(R.id.recycler_view);
      studentAdapter = new StudentAdapter(studentDataList,MainActivity.this);
      RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
      recyclerView.setLayoutManager(manager);
      recyclerView.setAdapter(studentAdapter);
      StudentDataPrepare();
      remove.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if(studentDataList.size()>0) {
               studentDataList.remove(studentDataList.size() - 1);
               studentAdapter.notifyDataSetChanged();
               Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
            }
         }
      });
      add.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if(studentDataList.size()> = 0) {
               studentData data = new studentData("raghu ram", 25);
               studentDataList.add(studentDataList.size(), data);
               studentAdapter.notifyDataSetChanged();
               Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
            }
         }
      });
   }
   @RequiresApi(api = Build.VERSION_CODES.N)
   private void StudentDataPrepare() {
      studentData data = new studentData("sai", 25);
      studentDataList.add(data);
      data = new studentData("sai raj", 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);
         }
      });
   }
}

위의 코드에서 우리는 리사이클러 보기와 학생 어댑터를 추가했습니다. 해당 학생 어댑터에서 우리는 studentDatalist를 arraylist로 전달했습니다. 학생 데이터 목록에는 학생의 이름과 나이가 포함됩니다. 추가 및 제거로 두 개의 버튼을 추가했습니다. 추가 버튼을 사용하여 아래와 같이 배열 목록에 항목을 추가할 수 있습니다. -

if(studentDataList.size()> = 0) {
   studentData data = new studentData("raghu ram", 25);
   studentDataList.add(studentDataList.size(), data);
   studentAdapter.notifyDataSetChanged();
   Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
}

위의 코드에서 우리는 arraylist 크기가 배열 목록에 데이터를 추가하고 notifyDataSetChanged()와 같은 특수 메서드를 사용한 것보다 0과 같거나 0보다 큰 것처럼 유효성 검사를 확인하고 있습니다. 이 메서드는 데이터 세트가 수정되어 어댑터가 내부적으로 보기를 새로 고칠 때 어댑터에 표시합니다.

배열 목록에서 데이터를 제거하기 위해 아래와 같이 arraylist와 함께 remove()를 사용했습니다. -

if(studentDataList.size()>0) {
   studentDataList.remove(studentDataList.size() - 1);
   studentAdapter.notifyDataSetChanged();
   Toast.makeText(MainActivity.this, String.valueOf(studentDataList.size()), Toast.LENGTH_LONG).show();
}

위의 코드에서 우리는 size-1을 기반으로 데이터를 제거하고 있습니다. 아래에서 데이터를 제거한다는 의미입니다. 데이터를 제거한 후 notifyDataSetChanged()를 사용하여 어댑터로 업데이트합니다.

5단계 − 다음은 수정된 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);
      }
   }
}   

어댑터 클래스에는 아래와 같이 네 가지 방법이 있습니다. -

  • onCreateViewHolder() :- 뷰 홀더를 생성하는 데 사용되며 뷰를 반환합니다.

  • onBindViewHolder() - 생성된 뷰 홀더와 바인딩됩니다.

  • getItemCount() - 목록의 크기를 포함합니다.

  • MyViewHolder 클래스 - RecyclerView.ViewHolder에 의해 확장된 뷰 홀더 내부 클래스입니다.

리사이클러 보기 항목에 임의의 배경을 설정하기 위해 임의의 클래스(Android에서 미리 정의된 클래스)를 사용하여 임의의 색상을 생성하고 아래와 같이 보기 항목의 상위 항목에 색상을 추가했습니다. -

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

6단계 − 다음은 res/layout/student_list_row.xml xml의 수정된 내용입니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:card_view = "https://schemas.android.com/apk/res-auto"
   android:layout_width = "match_parent"
   card_view:cardCornerRadius = "4dp"
   android:id = "@+id/card_view"
   android:layout_margin = "10dp"
   android:layout_height = "200dp">
   <LinearLayout
      android:id = "@+id/parent"
      android:layout_gravity = "center"
      android:layout_width = "match_parent"
      android:orientation = "vertical"
      android:gravity = "center"
      android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/name"
      android:layout_width = "wrap_content"
      android:gravity = "center"
      android:textSize = "25sp"
      android:textColor = "#FFF"
      android:layout_height = "wrap_content" />
   <TextView
      android:id = "@+id/age"
      android:layout_width = "wrap_content"
      android:gravity = "center"
      android:textSize = "25sp"
      android:textColor = "#FFF"
      android:layout_height = "wrap_content" />
   </LinearLayout>
</android.support.v7.widget.CardView>

위의 목록 항목 보기에서 우리는 cardview 내부에 이름과 나이에 대한 두 개의 텍스트 보기를 만들었습니다. 카드 보기에는 미리 정의된 모서리 반경과 그림자 속성이 포함되어 있습니다. 그래서 우리는 카드 보기에서 모서리 반경을 사용했습니다.

7단계 − 다음은 수정된 파일 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;
   }
}

위의 코드에서 학생 데이터 개체에 대해 알려줍니다. 응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -

Android에서 RecyclerView 어댑터 데이터를 업데이트하는 방법은 무엇입니까?

요소의 초기 끝은 25세의 sai raj이며 이제 아래와 같이 두 개의 요소를 추가합니다. -

Android에서 RecyclerView 어댑터 데이터를 업데이트하는 방법은 무엇입니까?

이제 모든 요소를 ​​제거하여 출력이 다음과 같아야 합니다. -

Android에서 RecyclerView 어댑터 데이터를 업데이트하는 방법은 무엇입니까?