[안드로이드 기본] 옵션메뉴 만들기Java/Android2020. 5. 18. 14:35
Table of Contents
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActiviy.java
package com.example.optionmenu2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//xml로 옵션메뉴 생성
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu); //각 항목이 눌러지만 토스트 메시지를 출력한다.
return true;
}
/*
//코드로 옵션메뉴 생성
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuItem item1 = menu.add(0,1,0,"사과");
item1.setIcon(R.drawable.ic_launcher_background);
item1.setAlphabeticShortcut('a');
menu.add(0,2,0,"포도").setIcon(R.drawable.ic_launcher_background);
menu.add(0,3,0,"바나나").setIcon(R.drawable.ic_launcher_background);
return true;
}
*/
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.apple :
Toast.makeText(this,"사과",Toast.LENGTH_SHORT).show();
return true;
case R.id.grape :
Toast.makeText(this,"포도",Toast.LENGTH_SHORT).show();
return true;
case R.id.banana :
Toast.makeText(this,"바나나",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
mymenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/apple"
android:icon="@drawable/ic_launcher_background"
android:title="사과"/>
<item
android:id="@+id/grape"
android:icon="@drawable/ic_launcher_background"
android:title="포도"/>
<item
android:id="@+id/banana"
android:icon="@drawable/ic_launcher_background"
android:title="바나나"/>
</menu>
반응형
'Java > Android' 카테고리의 다른 글
[안드로이드 기본] 커스텀 뷰를 사용하여 그리기 (0) | 2020.05.18 |
---|---|
[안드로이드 기본] 컨텍스트 메뉴 만들기 (0) | 2020.05.18 |
@반나무 :: 반나무_뿌리
3년차 WPF 개발자입니다.
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!