첫번째로 Create Project하고 화면 껍데기는 만들었음
이번에는 메뉴를 추가하고 Click 됐는지 확인만 한다.
총 15개의 TODO
<!--TODO (1) Add a string resource called search with the title "Search"-->
app > res > values > strings.xml에 search 라는 단어 추가
<resources> |
// Do 2 - 7 in menu.xml
// TODO (2) Create a menu xml called 'main.xml' in the res->menu folder
// TODO (3) Add one menu item to your menu
메뉴는 기본 프로젝트 생성에서 만들어지지 않기 때문에 직접 만들어야 한다.
왼쪽 프로젝트의 app 에서 오른쪽 버튼 클릭 Android Resource File 클릭
팝업으로 나타난 New Resource File 에
file name은 main으로 하고
Resouce type 은 Menu로 선택한다.(다른것을 선택하면 다른 폴더에 생성 됨)
생성이 끝나면 res > menu > main.xml 파일이 생성되어 있다.
여기에 사용할 menu를 정의한다.
// TODO (4) Give the menu item an id of @+id/action_search
// TODO (5) Set the orderInCategory to 1
// TODO (6) Show this item if there is room (use app:showAsAction, not android:showAsAction)
// TODO (7) Set the title to the search string ("Search") from strings.xml
main.xml 에서 item을 추가
menu item에 id 설정
정렬 순서(order in category) 설정
show as action 설정
버튼 text=search 설정 : string.xml에 있는 값을 사용
<?xml version="1.0" encoding="utf-8"?> |
다음부터는 MainActivity.java에서
// TODO (8) Override onCreateOptionsMenu
onCreateOptionsMenu method를 추가(Override)
import android.view.Menu; ... @Override |
// TODO (9) Within onCreateOptionsMenu, use getMenuInflater().inflate to inflate the menu
// TODO (10) Return true to display your menu
그 안에서 추가한 item 설정
전체소스: TODO 8,9,10
onCreateOptionsMenu 가 return type이 boolean이기 때문에
return true 또는 false로 지정해야함.
TODO 10에서 return true;로 하면서 화면에 보이도록 한다고 설정한 것임.
// TODO (8) Override onCreateOptionsMenu |
메뉴를 추가했으면 해당 메뉴를 선택했을 때 어떻게 동작하는지 정의가 필요
// TODO (11) Override onOptionsItemSelected
onOptionsItemSelected method를 추가(Override)
import android.view.MenuItem; ... @Override |
onOptionsItemSelected 안에서 선택된 item의 id를 확인하고
search 면 임시로 toast message 표시.
toast message 표시할 때에는 반드시 .show() 를 사용해야 함.
// TODO (12) Within onOptionsItemSelected, get the ID of the item that was selected
// TODO (13) If the item's ID is R.id.action_search, show a Toast and return true to tell Android that you've handled this menu click
// TODO (14) Don't forgot to call .show() on your Toast
// TODO (15) If you do NOT handle the menu click, return super.onOptionsItemSelected to let Android handle the menu click
import android.content.Context; ... // TODO (11) Override onOptionsItemSelected |
실행시켜보면
상단에 menu로 SEARCH 가 있고 그것을 클릭했을 때
toast message로 'Search clicked' 가 나타남.