AndroidでRecyclerViewアダプターデータを更新するにはどうすればよいですか?
例に入る前に、Androidのリサイクラービューとは何かを知っておく必要があります。リサイクラービューはリストビューのより高度なバージョンであり、ビューホルダーのデザインパターンに基づいて機能します。リサイクラービューを使用して、グリッドとアイテムのリストを表示できます。
この例は、年齢とともに学生の名前を表示する美しい学生記録アプリを作成して、RecyclerViewアダプターを更新する方法を示しています。
ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します。
ステップ2 − build.gradleを開き、リサイクラービューとカードビューライブラリの依存関係を追加します。
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>
上記のコードでは、相対的な親レイアウトとしてウィンドウマネージャーにリサイクラービューを追加し、追加と削除として2つのボタンを追加しました。 recyclerview adpterにデータを追加するための[追加]ボタンと、recyclerviewからデータを削除するための[削除]ボタン。
ステップ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);
}
});
}
} 上記のコードでは、リサイクラービューとstudentAdapterを追加しました。その学生アダプターでは、studentDatalistをarraylistとして渡しました。学生データリストには、学生の名前と年齢が含まれています。追加と削除として2つのボタンを追加しました。追加ボタンを使用して、以下に示すように配列リストにアイテムを追加できます-
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();
} 上記のコードでは、配列リストのサイズがゼロに等しいか、配列リストにデータを追加するよりもゼロより大きいかどうかの検証をチェックしており、notifyDataSetChanged()として特別なメソッドで使用しています。このメソッドは、データセットが変更されたときにアダプタに通知するため、アダプタは内部でビューを更新します。
配列リストからデータを削除するために、以下に示すように、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();
} 上記のコードでは、サイズ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);
}
}
} アダプタクラスには、以下に示す4つのメソッドがあります-
-
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 −以下は、xml res / layout/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>
上記のリストアイテムビューでは、カードビュー内に名前と年齢の2つのテキストビューを作成しました。カードビューには、事前定義されたコーナー半径とシャドウプロパティが含まれています。そのため、カードビューでコーナー半径を使用しました。
ステップ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 studioからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[実行]アイコンをクリックします。オプションとしてモバイルデバイスを選択し、デフォルトの画面を表示するモバイルデバイスを確認します-
要素の最初の終わりは25歳のsairajで、次のように2つの要素が追加されています-
すべての要素を削除して、出力が次のようになるようにします-
-
Androidでアプリを更新する方法
Android上のアプリは、機能を改善するためにアプリの開発者によってプッシュされた更新を定期的に受け取ります。多くの場合、セキュリティの更新だけでなく、安定性とパフォーマンスの向上ももたらします。デフォルトでは、Androidアプリは自動的に更新されますが、多くのユーザーは、このプロセスがいつどのように展開されるかについて、ある程度の制御を行うことができるかどうかを知りません。そのために、この記事では、Androidでアプリを自動的に更新して、その制御を取得する方法について説明します。 Androidでアプリを自動的に更新する方法 アプリが自動的に更新されるため、特定のアプリの新しいバージ
-
Android でデータをバインドする方法
データ バインディングは、視覚的なユーザー入力要素に情報 (データ) を接着するときに使用する手法です。このプロセスでは、入力が更新されるたびに、その背後にあるデータも更新されます。 これは決して新しい概念ではなく、これを設計に組み込んだフレームワークが多数あります (AngularJS/React/Vue など)。 この記事で注目するのは、フロントエンド フレームワークではなく、モバイル開発です。 Google は、Android Jetpack の一部である Data Binding Library を Android に導入しました。 Jetpack ライブラリ スイートに慣れ