AndroidStudio:Material な DropDownMenu を使ってみる

参考サイト様

https://material.io/components/menus/android#exposed-dropdown-menus

 

なんか選択肢だすやつ使ったことなかったし必要だったので使った。

選択肢用の layout 作成

TextView だけ入っていればよい。
list_item.xmlという名前にした。

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:ellipsize="end"
    android:maxLines="1"
    android:textAppearance="?attr/textAppearanceSubtitle1"
    />

Menu作成

適当な Activity にあてるための適当な layout にこいつを突っ込む。ID は任意

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/numberTypeMenu"
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/term_type"
    app:hintEnabled="true">

    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="none"
        />

</com.google.android.material.textfield.TextInputLayout>

Menu呼び出し

適当な Activity 内の onCreate() 関数内に書く。

   
enum class NumberType {
    ONE,TWO,THREE,FOUR
}     
onCreate(){//さっきの Menu に設定しておいた id
        val numberTypeMenu:TextInputLayout = findViewById(R.id.numberTypeMenu)
     val termTypeItems:MutableList<String> = mutableListOf()
        NumberType.values().forEach {
            numberItems.add(it.name)
        }
        val numberTypeAdapter = ArrayAdapter(this,R.layout.list_item,numberTypeItems)
        (numberTypeMenu.editText as? AutoCompleteTextView)?.setText(numberTypeItems[0])
        (numberTypeMenu.editText as? AutoCompleteTextView)?.setAdapter(numberTypeAdapter)
}

今回 Enum を使ったのは自分がよく使うから。別に Enum である必要はなく mutableList である必要もない。

Item を選択したときになにかしたい場合

var numberType:NumberType
(numberTypeMenu.editText as? AutoCompleteTextView)?.onItemClickListener =
OnItemClickListener(){adapterView, view, i, l ->
    numberType = enumValueOf(numberTypeAdapter.getItem(i)!!)
}

例はとりあえず選択している item の NumberType を取りたいときに使う。
OnItemClickListener 内でいろいろすることができる。

注意点

setText はデフォルトで設定したいものが設定されている。
setText を setAdapter の後にしてしまうと選択肢が setText で設定したものだけになってしまう。

 

感想戦

これと同じものを作るのはめんどくさいので今回は画像をとっていない。ちなみに自分は MaterialUI をあまり好いていない。デザインは楽してかっこよくできるけど Web 版だと DatePicker が有料だったりして、囲い込みの段階なのかなと思ってしまう。

最近データベース設計に悩んでいる。(まだ一回もしたことがない)
いつのまにか Room は Enum を勝手に変換してくれるようになっていた。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA