Computer >> कंप्यूटर ट्यूटोरियल >  >> प्रोग्रामिंग >> Android

Android में RecyclerView Adapter डेटा कैसे अपडेट करें?


परिचय

उदाहरण में जाने से पहले, हमें पता होना चाहिए कि Android में RecyclerView क्या है। RecyclerView ListView का अधिक उन्नत संस्करण है और यह View Holder डिज़ाइन पैटर्न पर आधारित काम करता है। RecyclerView का उपयोग करके हम ग्रिड और आइटम की सूची दिखा सकते हैं।

यह उदाहरण एक सुंदर छात्र रिकॉर्ड ऐप बनाकर दर्शाता है जो छात्र का नाम और उम्र प्रदर्शित करता है, और RecyclerView Adapter को कैसे अपडेट करें।

चरण 1: नया प्रोजेक्ट बनाएं

Android Studio में File → New Project पर जाएं और नया प्रोजेक्ट बनाने के लिए सभी आवश्यक विवरण भरें।

चरण 2: build.gradle में RecyclerView और CardView डिपेंडेंसी जोड़ें

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: 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>

उपरोक्त कोड में हमने RecyclerView को रिलेटिव पैरेंट लेआउट के रूप में विंडो मैनेजर में जोड़ा है और दो बटन Add और Remove जोड़े हैं। Add बटन RecyclerView Adapter में डेटा जोड़ेगा और Remove बटन RecyclerView से डेटा हटाएगा।

चरण 4: 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<StudentData> 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<StudentData>() {
            @Override
            public int compare(StudentData o1, StudentData o2) {
                return o1.name.compareTo(o2.name);
            }
        });
    }
}

उपरोक्त कोड में हमने RecyclerView और StudentAdapter जोड़ा है। उस Student Adapter में हमने StudentDataList को ArrayList के रूप में पास किया है। Student Data List में छात्र का नाम और उम्र होती है। हमने Add और Remove के रूप में दो बटन जोड़े हैं। Add बटन का उपयोग करके हम 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 का आकार शून्य के बराबर या उससे अधिक है तो हम ArrayList में डेटा जोड़ रहे हैं और हमने एक विशेष विधि notifyDataSetChanged() का उपयोग किया है। यह विधि Adapter को इंगित करती है कि डेटा सेट संशोधित हो गया है इसलिए Adapter आंतरिक रूप से व्यू को रीफ्रेश करेगा।

ArrayList से डेटा हटाने के लिए हमने remove() का उपयोग ArrayList के साथ किया है जैसा कि नीचे दिखाया गया है:

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() का उपयोग करके Adapter को अपडेट कर रहे हैं।

चरण 5: 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);
        }
    }
}

Adapter क्लास में चार विधियां हैं:

  • onCreateViewHolder() - व्यू होल्डर बनाने के लिए उपयोग किया जाता है और यह एक व्यू लौटाता है।
  • onBindViewHolder() - यह बनाए गए व्यू होल्डर के साथ बाइंड होता है।
  • getItemCount() - इसमें सूची का आकार होता है।
  • MyViewHolder क्लास - यह व्यू होल्डर इनर क्लास है जिसे RecyclerView.ViewHolder द्वारा एक्सटेंड किया गया है।

RecyclerView आइटम के लिए रैंडम बैकग्राउंड सेट करने के लिए, हमने Random क्लास (जो Android में पूर्वनिर्धारित क्लास है) का उपयोग करके रैंडम रंग उत्पन्न किए और व्यू आइटम के पैरेंट में रंग जोड़ा जैसा कि नीचे दिखाया गया है:

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

चरण 6: student_list_row.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 के अंदर नाम और उम्र के लिए दो TextViews बनाए हैं। CardView में पूर्वनिर्धारित कॉर्नर रेडियस और शैडो प्रॉपर्टी होती है। इसलिए हमने CardView के साथ कॉर्नर रेडियस का उपयोग किया है।

चरण 7: 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;
    }
}

उपरोक्त कोड Student Data ऑब्जेक्ट के बारे में सूचित करता है।

ऐप चलाएं

मान लें कि आपने अपना वास्तविक Android मोबाइल डिवाइस कंप्यूटर से कनेक्ट किया है। Android Studio से ऐप चलाने के लिए, अपनी प्रोजेक्ट की एक्टिविटी फ़ाइलों में से एक खोलें और टूलबार से Run आइकन पर क्लिक करें। अपने मोबाइल डिवाइस को विकल्प के रूप में चुनें और फिर अपना मोबाइल डिवाइस जांचें जो डिफ़ॉल्ट स्क्रीन प्रदर्शित करेगा:

Android में RecyclerView Adapter डेटा कैसे अपडेट करें?

प्रारंभ में अंतिम तत्व sai raj है जिसकी उम्र 25 है, अब दो तत्व जोड़ रहे हैं जैसा कि नीचे दिखाया गया है:

Android में RecyclerView Adapter डेटा कैसे अपडेट करें?

अब सभी तत्वों को हटा रहे हैं इसलिए आउटपुट ऐसा होना चाहिए:

Android में RecyclerView Adapter डेटा कैसे अपडेट करें?

  1. Android TextView में टेक्स्ट को जस्टिफाई कैसे करें? Android TextView में टेक्स्ट को जस्टिफाई कैसे करें?

    यह उदाहरण दर्शाता है कि Android में TextView में टेक्स्ट को जस्टिफाई (दोनों किनारों पर अलाइन) कैसे किया जाता है। समस्या Android का स्टैंडर्ड TextView android:gravity=center_horizontal या left|right से जस्टिफिकेशन सपोर्ट नहीं करता। API 26 (Android 8.0) से android:justificationMode=inter_word उपलब्ध

  1. एंड्रॉइड पर अपने ऐप्स कैसे अपडेट करें एंड्रॉइड पर अपने ऐप्स कैसे अपडेट करें

    आपके एंड्रॉइड पर ऐप्स को ऐप्स के डेवलपर्स द्वारा नियमित रूप से अपडेट प्राप्त होते हैं ताकि उनकी कार्यक्षमता में सुधार किया जा सके। वे अक्सर स्थिरता और प्रदर्शन सुधार के साथ-साथ सुरक्षा अपडेट भी लाते हैं। डिफ़ॉल्ट रूप से, एंड्रॉइड ऐप्स खुद को ऑटोमैटिकली अपडेट कर लेते हैं, लेकिन कई उपयोगकर्ता नहीं जान

  1. Android Data Binding मास्टर करें: सहज UI डेटा एकीकरण Android Data Binding मास्टर करें: सहज UI डेटा एकीकरण

    डेटा बाइंडिंग एक तकनीक है जिसका उपयोग तब किया जाता है जब आप सूचना के टुकड़ों (आपके डेटा) को कुछ विज़ुअल उपयोगकर्ता इनपुट तत्वों से जोड़ना चाहते हैं। इस प्रक्रिया में, जब भी इनपुट अपडेट होता है, तो उसके पीछे का डेटा भी अपडेट हो जाता है। यह कोई नई अवधारणा नहीं है, और ऐसे ढेर सारे फ्रेमवर्क हैं जिन्हें