1
0

More than 3 years have passed since last update.

[ Android ] AlertDialogにListViewを表示する2(完成)

Posted at

前回の記事ではエラーが発生して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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0