【Android】AlertDialogのリスト表示で、ArrayList<String>が渡せずエラーが出た場合の対処法
notwork_android_listdialog
スポンサーリンク

リスト項目選択ダイアログで動的な文字列配列を表示する方法

None of the following functions can be called with the arguments supplied.

ヒーラー
AlertDialogに文字列配列を表示したいだけなのだが直感的な使い方ができない

はじめに

リスト項目選択ダイアログは以下の要領で作成できます。
ラジオボタンやチェックボックスを使用したリスト表示も同様、setItems()を使用します。

val items = arrayOf("アイテム1", "アイテム2", "アイテム3", "アイテム4")
AlertDialog.Builder(requireContext()).setTitle("リストタイトル").setItems(items) { dialog, which ->
    //TODO: 項目選択後の処理
}.setNegativeButton("キャンセル", null).create().show()
AlertDialog.Builder(requireContext()).setTitle("リストタイトル").setItems(R.array.items) { dialog, which ->
    //TODO: 項目選択後の処理
}.setNegativeButton("キャンセル", null).create().show()
リストダイアログ

このように固定の静的な配列においては、setItems()を使って手軽にリスト表示をすることが可能です。
しかしながら、以下のような動的に作成された文字列の配列では、上記のように簡単にはいきません。

問題

出し入れ可能な配列は一般的にArrayList<String>を用いることが多いと思います。
しかし、ArrayList<String>をそのままsetItems()に設定すると、エラーとなります。

val items: ArrayList<String>
...
AlertDialog.Builder(requireContext()).setTitle("リストタイトル").setItems(items) { dialog, which ->
    //TODO: 項目選択後の処理
}.setNegativeButton("キャンセル", null).create().show()
エラーメッセージ
None of the following functions can be called with the arguments supplied.
 setItems(Array<(out) CharSequence!>!, DialogInterface.OnClickListener!) defined in androidx.appcompat.app.AlertDialog.Builder
 setItems(Int, DialogInterface.OnClickListener!) defined in androidx.appcompat.app.AlertDialog.Builder

対処方法

要はsetItems()に渡すべき型は、Array<CharSequence!>!である必要があります。
しかし、単にitems.toArray()しただけでは、型が確定せず不十分です。
ここが直感的にいかないもどかしいところです。

調べるとここでつまずいている例は多いようでした。
アダプターで対応する例もありますが、setItems()があるのに使えない気持ち悪さがあります。
そこでsetItems()でも以下の対応でArray<CharSequence!>!が明示的にできることで解決します。

val items = ArrayList<String>()
...
val array: Array<CharSequence> = items.toArray(arrayOfNulls(0))
AlertDialog.Builder(requireContext()).setTitle("リストタイトル").setItems(array) { dialog, which ->
    //TODO: 項目選択後の処理
}.setNegativeButton("キャンセル", null).create().show()

Array<CharSequence!>!が明示的にできれば良いので、以下の方法でも可能です。

val array: Array<CharSequence> = items.toArray(arrayOfNulls(0))
↓
val array = items.toArray(arrayOfNulls<CharSequence>(0))

尚、以下のようにsetAdapter()で対応することもできます。

val items = ArrayList<String>()
...
AlertDialog.Builder(requireContext()).setTitle("リストタイトル").setAdapter(ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, items)) { dialog, which ->
    //TODO: 項目選択後の処理
}.setNegativeButton("キャンセル", null).create().show()

スポンサーリンク

Twitterでフォローしよう

おすすめの記事