-
[6] MenuDevelpment/Android Using Sample 2020. 9. 13. 21:35
1. Menu
menu
123456789101112<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:id="@+id/menu1"android:title="menu1"/><itemandroid:id="@+id/menu2"android:title="menu2"/></menu>cs * res/menu : res에 menu 디렉토리를 생성하고, menu 디렉토리에서 Menu Resource File을 추가.
* 추가하고 싶은 개수 만큼 item을 만들고, id, title 설정.
Activity
123456789101112131415public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.menu, menu);return true;}}cs * onCreateOptionMenu 를 Override 한다.
* getMenuInflater() 를 호출하여 추가.
2. 결과화면
3. Menu Click Event
Activity
1234567891011121314151617181920212223242526272829303132public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.menu, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch( item.getItemId() ){case R.id.menu1://menu1 EventToast.makeText(getApplicationContext(), "menu1", Toast.LENGTH_SHORT).show();break;case R.id.menu2://menu2 Eventbreak;}return super.onOptionsItemSelected(item);}}cs * onOptionsItemSelected 를 Override.
* item.getItemId() 로 해당 menu의 id를 가져와서 처리.
4. 결과화면
'Develpment > Android Using Sample' 카테고리의 다른 글
[8] Dialog (0) 2020.09.13 [7] Alert Dialog (0) 2020.09.13 [5] Image Button Effect (drawable) (0) 2020.09.13 [4] Custom Button (0) 2020.09.13 [3] ListView (0) 2020.09.13