質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Q&A

解決済

1回答

1090閲覧

複数のチェックボックスの値を取得してToastを表示したい

BIWD

総合スコア10

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

2グッド

1クリップ

投稿2023/01/16 06:50

編集2023/01/16 07:00

前提

チェックボックスを増やしたり消したりするプログラムです。

実現したいこと

複数のチェックボックスの状態を取得して、1つでもチェックがついていなかったら”忘れ物があります”のToastを出したいです。

発生している問題・エラーメッセージ

現在表示されているチェックボックスすべての値を取得したいのですが、1つ目のものしか取得できません。

該当のソースコード

MainActivity.java

1package com.example.check3; 2 3import androidx.annotation.NonNull; 4import androidx.appcompat.app.AlertDialog; 5import androidx.appcompat.app.AppCompatActivity; 6import androidx.recyclerview.widget.RecyclerView; 7 8import android.content.DialogInterface; 9import android.content.SharedPreferences; 10import android.os.Bundle; 11import android.preference.Preference; 12import android.preference.PreferenceManager; 13import android.view.LayoutInflater; 14import android.view.View; 15import android.view.ViewGroup; 16import android.widget.Button; 17import android.widget.CheckBox; 18import android.widget.EditText; 19import android.widget.LinearLayout; 20import android.widget.TextView; 21 22import java.util.ArrayList; 23import java.util.List; 24import java.util.StringJoiner; 25 26 27import android.content.SharedPreferences; 28import android.os.Bundle; 29import android.view.*; 30import android.widget.*; 31 32import androidx.annotation.NonNull; 33import androidx.appcompat.app.*; 34import androidx.recyclerview.widget.RecyclerView; 35 36import java.util.*; 37 38public class MainActivity extends AppCompatActivity { 39 @Override 40 protected void onCreate(Bundle savedInstanceState) { 41 super.onCreate(savedInstanceState); 42 setContentView(R.layout.activity_main); 43 44 RecyclerView list = findViewById(R.id.list); 45 Adapter adapter = new Adapter(getPreferences(MODE_PRIVATE), "current"); 46 list.setAdapter(adapter); 47 48 Button add = findViewById(R.id.add); 49 add.setOnClickListener(v -> { 50 View view = getLayoutInflater().inflate(R.layout.dialog, null, false); 51 EditText name = view.findViewById(R.id.nameEdit); 52 new AlertDialog.Builder(MainActivity.this) 53 .setView(view) 54 .setTitle("もちものついか") 55 .setPositiveButton("ついか", (d,i) -> adapter.add(name.getText().toString())) 56 .setNegativeButton("やめる", null) 57 .create() 58 .show(); 59 }); 60 } 61 62 private static class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { 63 private class ViewHolder extends RecyclerView.ViewHolder { 64 final CheckBox nameView; 65 public ViewHolder(@NonNull View itemView) { 66 super(itemView); 67 nameView = itemView.findViewById(R.id.name); 68 Button delete = itemView.findViewById(R.id.delete); 69 delete.setOnClickListener(v -> remove(getAdapterPosition())); 70 } 71 } 72 73 private final SharedPreferences pref; 74 private final String prefKey; 75 private final List<String> list = new ArrayList<>(); 76 77 Adapter(SharedPreferences pref, String prefKey) { 78 this.pref = pref; 79 this.prefKey = prefKey; 80 81 String value = pref.getString(prefKey, null); 82 if(value != null) { 83 for(String name : value.split(",")) list.add(name); 84 } 85 } 86 87 void add(String name) { 88 list.add(name); 89 store(); 90 notifyItemInserted(list.size() - 1); 91 } 92 93 void remove(int position) { 94 if(position < 0) return; 95 list.remove(position); 96 store(); 97 notifyItemRemoved(position); 98 } 99 100 private void store() { 101 pref.edit().putString(prefKey, getValue()).commit(); 102 } 103 104 private String getValue() { 105 if(list.isEmpty()) return null; 106 StringJoiner sj = new StringJoiner(","); 107 for(String value : list) sj.add(value); 108 return sj.toString(); 109 } 110 111 @NonNull 112 @Override 113 public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 114 return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card, null, false)); 115 } 116 117 @Override 118 public void onBindViewHolder(@NonNull ViewHolder holder, int position) { 119 holder.nameView.setText(list.get(position)); 120 } 121 122 @Override 123 public int getItemCount() { 124 return list.size(); 125 } 126 } 127}

activity_main.xml

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <androidx.recyclerview.widget.RecyclerView 10 android:id="@+id/list" 11 android:layout_width="match_parent" 12 android:layout_height="match_parent" 13 android:layout_marginBottom="70dp" 14 app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 15 app:layout_constraintBottom_toTopOf="@id/add" 16 app:layout_constraintEnd_toEndOf="parent" 17 app:layout_constraintStart_toStartOf="parent" 18 app:layout_constraintTop_toTopOf="parent" /> 19 20 <Button 21 android:id="@+id/add" 22 android:layout_width="80dp" 23 android:layout_height="80dp" 24 android:layout_marginBottom="10dp" 25 android:scaleType="fitCenter" 26 android:text="+ついか" 27 app:layout_constraintBottom_toBottomOf="parent" 28 app:layout_constraintEnd_toEndOf="parent" 29 app:layout_constraintStart_toStartOf="parent" /> 30 31 <Button 32 android:id="@+id/isg" 33 android:layout_width="wrap_content" 34 android:layout_height="wrap_content" 35 android:text="GO!!!!" 36 app:layout_constraintBottom_toBottomOf="parent" 37 app:layout_constraintHorizontal_bias="0.498" 38 app:layout_constraintLeft_toLeftOf="parent" 39 app:layout_constraintRight_toRightOf="parent" 40 app:layout_constraintTop_toTopOf="parent" 41 app:layout_constraintVertical_bias="0.834"></Button> 42 43</androidx.constraintlayout.widget.ConstraintLayout>

card.xml

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" 6 android:layout_margin="10dp" 7 app:cardCornerRadius="10dp" 8 app:cardElevation="10dp"> 9 10 <RelativeLayout 11 android:layout_width="match_parent" 12 android:layout_height="wrap_content" 13 android:padding="10dp"> 14 15 <CheckBox 16 android:id="@+id/name" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:layout_margin="10dp" 20 android:padding="5dp" 21 android:textColor="#808080" 22 android:textSize="20dp" /> 23 24 <Button 25 android:id="@+id/delete" 26 android:layout_width="50dp" 27 android:layout_height="50dp" 28 android:textColor="#808080" 29 android:backgroundTint="#FFFACD" 30 android:layout_alignParentEnd="true" 31 android:layout_alignParentRight="true" 32 android:text="✖" /> 33 34 </RelativeLayout> 35 36</androidx.cardview.widget.CardView>

dialog.xml

1<?xml version="1.0" encoding="utf-8"?> 2<RelativeLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 <RelativeLayout 7 android:layout_width="match_parent" 8 android:layout_height="wrap_content" 9 android:padding="10dp"> 10 11 <EditText 12 android:id="@+id/nameEdit" 13 android:layout_width="match_parent" 14 android:layout_height="wrap_content" 15 android:hint="✏ ここににゅうりょく" 16 android:textSize="20dp"/> 17 18 </RelativeLayout> 19 20</RelativeLayout>

試したこと

findViewById(R.id.isg).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox ch1 = findViewById(R.id.name);
if(ch1.isChecked() == false){
Toast toast = Toast.makeText(MainActivity.this, "忘れ物があるよ", Toast.LENGTH_LONG);
toast.show();
}else{
return;
}
}
}
);
を足してみましたが一つ目のチェックボックスでしか反映されていませんでした。

補足情報(FW/ツールのバージョンなど)

Nexus 6P API28 を使用しています。

meielle, BEWD👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2023/01/16 06:57 編集

コードはファイル毎にコードのマークダウン( ``` だけの行)で囲ってください。コードのマークダウンを使わないと一部の記号がフォーマットに使用されて、コピペしても動かない場合があります。 カードとダイアログのイメージが逆のようです。(xml があればイメージ画像は要らないかもしれません。)
BIWD

2023/01/16 07:01

丁寧に教えてくださりありがとうございます。 不慣れで申し訳ございませんが、修正させていただきました。 お手数をおかけしました。
jimbe

2023/01/16 07:24

修正ありがとうございます。
guest

回答1

0

ベストアンサー

まず、 Adapter に(持ち物名の他に)チェック状態を保持する必要があります。
Item クラスを作って List<String> を List<Item> とし、 list を処理している個所を修正します。

MainActivity.Adapter に追加

java

1 private static class Item { 2 final String name; 3 boolean checked = false; 4 Item(String name) { 5 this.name = name; 6 } 7 }

MainActivity.Adapter の一部修正
フィールド

java

1 private final List<Item> list = new ArrayList<>(); //修正

コンストラクタ

java

1 Adapter(SharedPreferences pref, String prefKey) { 2 this.pref = pref; 3 this.prefKey = prefKey; 4 5 String value = pref.getString(prefKey, null); 6 if(value != null) { 7 for(String name : value.split(",")) list.add(new Item(name)); //修正 8 } 9 }

メソッド

java

1 void add(String name) { 2 list.add(new Item(name)); //修正 3 store(); 4 notifyItemInserted(list.size() - 1); 5 } 6 7 private String getValue() { 8 if(list.isEmpty()) return null; 9 StringJoiner sj = new StringJoiner(","); 10 for(Item item : list) sj.add(item.name); //修正 11 return sj.toString(); 12 } 13 14 @Override 15 public void onBindViewHolder(@NonNull ViewHolder holder, int position) { 16 Item item = list.get(position); //追加 17 holder.nameView.setText(item.name); //修正 18 holder.nameView.setChecked(item.checked); //追加 19 }

そして、チェックボタンの操作によってそれを更新するようにします。

MainActivity.Adapter に追加

java

1 void setCheck(int position, boolean checked) { 2 if(list.get(position).checked != checked) { 3 list.get(position).checked = checked; 4 notifyItemChanged(position); 5 } 6 }

MainActivity.Adapter.ViewHolder

java

1 private class ViewHolder extends RecyclerView.ViewHolder { 2 final CheckBox nameView; 3 public ViewHolder(@NonNull View itemView) { 4 super(itemView); 5 nameView = itemView.findViewById(R.id.name); 6 nameView.setOnCheckedChangeListener((v,checked) -> setCheck(getAdapterPosition(),checked)); //行追加 7 Button delete = itemView.findViewById(R.id.delete); 8 delete.setOnClickListener(v -> remove(getAdapterPosition())); 9 } 10 }

最後に、list のチェック状態を返すメソッドを作り、ボタン押下でそれを読んでトーストを表示させます。
MainActivity.Adapter に追加

java

1 boolean checkAll() { 2 for(Item item : list) if(!item.checked) return false; 3 return true; 4 }

MainActivity#onCreate() に追加

java

1 Button isg = findViewById(R.id.isg); 2 isg.setOnClickListener(v -> { 3 if(!adapter.checkAll()) { 4 Toast.makeText(MainActivity.this, "忘れ物があるよ", Toast.LENGTH_LONG).show(); 5 } 6 });

投稿2023/01/16 08:28

編集2023/01/16 16:29
jimbe

総合スコア12632

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

BIWD

2023/01/17 01:18

回答ありがとうございます。 いただいたプログラムを実装してみたところ、無事に動かすことができたので、ベストアンサーとさせていただきます。 分かりやすい説明を一つ一つに付けていただいたおかげで初心者の私にも理解することができました。 助けていただいて本当にありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問