์๋๋ก์ด๋ ์กํฐ๋นํฐ ํ๋ฉด ์ฑ๋ฐ(์ ํํ๋ ํด๋ฐ)์ ๋ฒํผ์ ๋ง๋ค์ด์ฃผ๋ ค๊ณ ํ๋ค. ๋ฒํผ ํ๋์ด๊ธฐ ๋๋ฌธ์ ํ๊ฐ์ง์ ๊ธฐ๋ฅ๋ง ํ๋ค.
1. Menu Resource File ์์ฑ
app์ res/menu ํด๋์์ ๋ฉ๋ชจ ๋ฆฌ์์ค xml ์์ฑ
๊ทธ๋ผ ์๋ ๊ฒ ๋จ๋๋ฐ, ์ผ์ชฝ์ ๋ฉ๋ด Menu Item์ ์ปดํผ๋ํธ ํธ๋ฆฌ/menu ์์ ๋ฃ์ด ์๋ก ์์ฑํ๋ค.
๊ทธ๋ผ ์ด๋ ๊ฒ ๋๋กญ๋ฉ๋ด๊ฐ ๊ธฐ๋ณธ์ผ๋ก ์์ฑ๋๋๋ฐ, ๋๋ ๋ฒํผ๋ง ์ํ๋ ๋๋กญ๋ฉ๋ด๋ฅผ ์์ ์ฃผ๊ฒ ๋ค.
๊ทธ๋ฌ๊ธฐ ์ํด xml ์ฝ๋๋ฅผ ์ฐ๋ค.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Item" />
</menu>
์๋์ ๊ฐ์ด ๋ฐ๊ฟ์ฃผ์๋ค.
<menu 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"
tools:context="์ด ๋ฉ๋ด๋ฅผ ์ฌ์ฉํ ์กํฐ๋นํฐ๊ฒฝ๋ก">
<item
android:id="@+id/action_save"
android:orderInCategory="100"
android:title="SAVE"
app:showAsAction="always" />
</menu>
์กํฐ๋นํฐ ๊ฒฝ๋ก ์์ (app/java ํ์ ํด๋ ์ด๋ฆ)
tools:context = "com.example.myproject.MainActivity"
title ๋์ icon์ ์ง์ ํด์ฃผ์ด๋ ๋๋ค. title๊ณผ icon ๋๋ค ์ง์ ํ๋ค๋ฉด icon๋ง ๋ณด์ธ๋ค.
<item
android:id="@+id/action_save"
android:icon="@android:drawable/ic_menu_save"
android:title="SAVE"
android:orderInCategory="100"
app:showAsAction="always" />
2. Activity์ ๋ฉ๋ด ๋ฆฌ์์ค ์ง์
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.๋ฉ๋ด๋ฆฌ์์คํ์ผ๋ช
, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.๋ฉ๋ด๋ฆฌ์์ค์ ๋ฒํผID๊ฐ:
//๋์๋ด์ฉ
return true;
}
return super.onOptionsItemSelected(item);
}
๋ฉ๋ด๋ฅผ ์ฌ์ฉํ ์กํฐ๋นํฐ ํด๋์ค์ onCreateOptionsMenu, onOptionsItemSelected ํจ์๋ฅผ ์ค๋ฒ๋ผ์ดํธํด์ค๋ค.
์ง์ ์ฝ๋๋ฅผ ์์ฑํด๋๋์ง๋ง, ๋ง์ฐ์ค ์ฐํด๋ฆญ>Generate...>Override Methods... ๋ก๋ ๋ง๋ค ์ ์๋ค.
์๋๋ ์์ ๋ด๊ฐ ์ง์ ํ ๋ฒํผ ID๋ก ์์ฑํ๊ณ , ๋ค๋ก๊ฐ๊ธฐ ๋ฒํผ๋ ๋ฃ์ ๋ชจ์ต์ด๋ค.
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_save:
//๋์
return true;
}
๋๋ ค๋ณด๋ ์ ๋ํ๋๋ค.