LoginSignup
0
1

More than 3 years have passed since last update.

【Android】Kotlinでメニュー機能作成

Last updated at Posted at 2021-01-15

ペットの年齢を人間の年齢に換算するアプリを作成していて、
onOptionsItemSelected部分の機能を忘れそうだったので、
覚書として記載。
なるべくシンプルな内容になるように心掛けて書いてみた。

全ソース:
https://github.com/CoffCookie/pet_age_conversion

素材提供元
ぱくたそ:
https://www.pakutaso.com/

画面作成

Menuのxmlファイル作成
resディレクトリで右クリックし、New→Android Resource Fileを選択。
File name:pet_select
Resource type: Menu

を選択し、OKをクリックします。

その後は
app/src/main/res/menu/pet_select.xml
app/src/main/res/layout/activity_main.xml

でそれぞれ画面作成を行います。
ソースコードはgithubをご覧ください。

スクリーンショット 2021-01-14 18.21.40.jpg

処理部分作成

スクリーンショット 2021-01-15 12.58.36.png

app/src/main/res/menu/pet_select.xml
で今回それぞれ、
idを
cat_text
dog_text
と指定した。

onOptionsItemSelectedで、
R.id.cat_text
R.id.dog_text
とそれぞれ指定。

これで、それぞれのメニューで選択出来るようになる。

MainActivity.kt
//メニュー表示
override fun onCreateOptionsMenu(menu: Menu?):Boolean {
    menuInflater.inflate(R.menu.pet_select,menu)
...
}

//選択した時の処理
override fun onOptionsItemSelected(item: MenuItem): Boolean {
...
    when(item?.itemId){
        R.id.cat_text -> {
          //猫の年齢を計算する処理
        }
        R.id.dog_text -> {
          //犬の年齢を計算する処理
        }
    }
    return super.onOptionsItemSelected(item)
}
0
1
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
0
1