Androidの学習をはじめて7日くらいの人の問題集

Android

ListViewのデータ登録と削除。DialogFragmentとActivity間でのデータの受け渡し練習。

Q1
フォームよりリストビューにデータを登録できるようにする。
リストビューに登録されたデータは、クリックすると下部にその単語の意味を表示。
ロングクリックで項目を削除できるようにせよ。
削除の際には確認のダイアログを表示すること。

[実行例]

スタート画面

フォームにデータを入力する。

登録ボタンを押すとリストに登録される。

項目をクリックすると下部にその単語の意味が表示される。
(下図はword2をクリックした場合)

項目を長押しすると確認のダイアログを表示する
(下図はword2を長押しした場合)

はいを押すと項目が削除される

●activity_main.xml

01<?xml version="1.0" encoding="utf-8"?>
02<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    xmlns:app="http://schemas.android.com/apk/res-auto"
04    android:layout_width="match_parent"
05    android:layout_height="match_parent"
06    >
07 
08    <ListView
09        android:layout_width="0dp"
10        android:layout_height="200dp"
11        android:layout_marginLeft="8dp"
12        android:layout_marginRight="8dp"
13        android:layout_marginTop="8dp"
14        app:layout_constraintLeft_toLeftOf="parent"
15        app:layout_constraintRight_toRightOf="parent"
16        app:layout_constraintTop_toTopOf="parent"
17        android:id="@+id/lv" />
18 
19    <TextView
20        android:id="@+id/tvResult"
21        android:layout_width="wrap_content"
22        android:layout_height="wrap_content"
23        android:layout_marginLeft="8dp"
24        android:layout_marginRight="8dp"
25        android:layout_marginTop="16dp"
26        android:textSize="18sp"
27        app:layout_constraintLeft_toLeftOf="parent"
28        app:layout_constraintRight_toRightOf="parent"
29        app:layout_constraintTop_toBottomOf="@+id/lv" />
30 
31    <TextView
32        android:id="@+id/textView2"
33        android:layout_width="wrap_content"
34        android:layout_height="wrap_content"
35        android:layout_marginLeft="8dp"
36        android:text="単語"
37        app:layout_constraintLeft_toLeftOf="parent"
38        app:layout_constraintBaseline_toBaselineOf="@+id/etWord" />
39 
40    <EditText
41        android:id="@+id/etWord"
42        android:layout_width="wrap_content"
43        android:layout_height="wrap_content"
44        android:ems="10"
45        android:inputType="text"
46        android:text=""
47        app:layout_constraintLeft_toRightOf="@+id/textView2"
48        android:layout_marginLeft="8dp"
49        android:layout_marginTop="8dp"
50        app:layout_constraintTop_toBottomOf="@+id/tvResult" />
51 
52    <TextView
53        android:id="@+id/textView3"
54        android:layout_width="wrap_content"
55        android:layout_height="wrap_content"
56        android:layout_marginLeft="8dp"
57        android:text="意味"
58        app:layout_constraintLeft_toLeftOf="parent"
59        app:layout_constraintBaseline_toBaselineOf="@+id/etBody" />
60 
61    <EditText
62        android:id="@+id/etBody"
63        android:layout_width="wrap_content"
64        android:layout_height="wrap_content"
65        android:ems="10"
66        android:inputType="text"
67        android:text=""
68        android:layout_marginTop="8dp"
69        app:layout_constraintTop_toBottomOf="@+id/etWord"
70        app:layout_constraintLeft_toRightOf="@+id/textView3"
71        android:layout_marginLeft="8dp" />
72 
73    <Button
74        android:id="@+id/button"
75        android:layout_width="wrap_content"
76        android:layout_height="wrap_content"
77        android:layout_marginLeft="8dp"
78        android:layout_marginRight="8dp"
79        android:layout_marginTop="8dp"
80        android:onClick="btRegister"
81        android:text="登録"
82        app:layout_constraintLeft_toLeftOf="parent"
83        app:layout_constraintRight_toRightOf="parent"
84        app:layout_constraintTop_toBottomOf="@+id/etBody" />
85</android.support.constraint.ConstraintLayout>

●MainActivity.java

001import android.app.Dialog;
002import android.app.DialogFragment;
003import android.content.DialogInterface;
004import android.os.Bundle;
005import android.support.v7.app.AlertDialog;
006import android.support.v7.app.AppCompatActivity;
007import android.view.View;
008import android.widget.AdapterView;
009import android.widget.ArrayAdapter;
010import android.widget.EditText;
011import android.widget.ListView;
012import android.widget.TextView;
013import android.widget.Toast;
014 
015import java.io.Serializable;
016import java.util.ArrayList;
017import java.util.List;
018 
019public class MainActivity extends AppCompatActivity {
020    private ListView lv;
021    private EditText etWord,etBody;
022    private TextView tvResult;
023    private List<Word> list=new ArrayList<>();
024    private ArrayAdapter<Word> adapter;
025 
026    @Override
027    protected void onCreate(Bundle savedInstanceState) {
028        super.onCreate(savedInstanceState);
029        setContentView(R.layout.activity_main);
030        //findView
031        lv=(ListView)findViewById(R.id.lv);
032        etWord=(EditText)findViewById(R.id.etWord);
033        etBody=(EditText)findViewById(R.id.etBody);
034        tvResult=(TextView)findViewById(R.id.tvResult);
035        //adapter生成
036        adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
037        //リストビュー表示
038        lv.setAdapter(adapter);
039        //クリックリスナー登録
040        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
041            @Override
042            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
043                //positionからWordインスタンスを取得
044                Word w=list.get(position);
045                //テキストビューに表示
046                tvResult.setText(w.getBody());
047            }
048        });
049        //長押しリスナー登録
050        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
051            @Override
052            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
053                //Wordインスタンス取得
054                Word word=list.get(position);
055                //ダイアログフラグメントをnew
056                DialogFragment dialog=new MyDialog();
057                //バンドルオブジェクトを生成
058                Bundle b=new Bundle();
059                //インスタンスを送るにはputSerializable
060                b.putSerializable("word",word);
061                //バンドルがセットされる。
062                dialog.setArguments(b);
063                //ダイアログ表示
064                dialog.show(getFragmentManager(),"tag");
065                //イベント消費する。
066                return true;
067            }
068        });
069 
070    }
071    //ボタンが押された時の処理
072    public void  btRegister(View v){
073        //エディットテキストから情報を収集
074        String word=etWord.getText().toString();
075        String body=etBody.getText().toString();
076        //情報からインスタンスを生成してリストに登録する。
077        list.add(new Word(word,body));
078        //リストに変更があったことをアダプターに知らせる(再描画
079        adapter.notifyDataSetChanged();
080        //項目を空に
081        etWord.setText("");
082        etBody.setText("");
083        //フォーカスを移す
084        etWord.requestFocus();
085 
086    }
087    //リストビューから引数で渡されたインスタンスを削除するメソッド
088    public void removeList(Word word){
089        //アダプターからremove(インスタンス)すればOK
090        adapter.remove(word);
091        //テキストビューを空に
092        tvResult.setText("");
093        //Toastで文言表示
094        Toast.makeText(this,word+"を削除しました",Toast.LENGTH_SHORT).show();
095    }
096    //クラス間をまたいで送信される場合はSerializableインターフェイスを実装する。
097    public static class Word implements Serializable{
098        private String word;
099        private String body;
100        public Word(String word,String body){
101            this.word=word;
102            this.body=body;
103        }
104        //標準出力を設定
105        @Override
106        public String toString() {
107            return this.word;
108        }
109        public String getBody(){
110            return this.body;
111        }
112    }
113    //ダイアログフラグメントクラス
114    public static class MyDialog extends android.app.DialogFragment{
115        //onCreateDialogをオーバーライドする。
116        @Override
117        public Dialog onCreateDialog(Bundle savedInstanceState) {
118 
119            //バンドルされたオブジェクト取得
120            final Word word=(Word)(getArguments().getSerializable("word"));
121            //上記処理を省略せずに書くと以下
122//            Bundle b=this.getArguments();
123//            Serializable s=b.getSerializable("word");
124//            final Word word=(Word)s;
125 
126            //ダイアログはAlertDialog.Builderクラスのインスタンスを最初に作る
127            AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
128            //builderインスタンを用いてダイアログの設定
129            builder.setTitle("確認")
130                    .setMessage("["+word+"]を本当に削除してよろしいですか?")
131                    .setPositiveButton("yes", new DialogInterface.OnClickListener() {
132                        @Override
133                        public void onClick(DialogInterface ialog, int which) {
134                            //組み込まれたアクティビティーを取得
135                            MainActivity activity=(MainActivity)getActivity();
136                            //そこにあるremoveListを実行
137                            activity.removeList(word);
138                        }
139                    })
140                    .setNegativeButton("no", new DialogInterface.OnClickListener() {
141                        @Override
142                        public void onClick(DialogInterface dialog, int which) {
143 
144                        }
145                    });
146            //builder.createでダイアログが作成される。
147            return builder.create();
148        }
149    }
150}

コメント

タイトルとURLをコピーしました