前回の記事ではエラーが発生してListViewを表示できなかった。
https://qiita.com/QiitaD/items/0713d7565ada707133e5
起こったエラー
「java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.」が発生した。
このエラーの意味(参考URL参照)は
「親Viewが子Viewを管理しています!
それに反することをすると、当然動かなくなるよ!(=_=メ)」
らしい…
コードをチェック
自分のコードを見てみると親クラス(MainActivity)がもつリストビューの用語IDを取得して、それをAlertDialogにセットしようとしていた。これが原因であった。
listViewFruits_ = findViewById(R.id.listView);//親クラスのレイアウトからListView取得
//
//アダプターやリストの作成・・・
//
listViewFruits_.setAdapter(myAdapter);
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("タイトル")
.setView(listViewFruits_)//親クラスのレイアウトセットできない
.create();
alertDialog.show();
そこで
listViewFruits_ = findViewById(R.id.listView);
の行を以下のようにnewすることで解決できた。
listViewFruits_ = new ListView(this);
感想
今回はListViewとAlertDialogであったが、調査したところ他にも起こる事例があったので、ぜひ参考にしていただきたい。
参考URL
・エラーの意味
http://www.sumahodays.sblo.jp/article/105586834.html