ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [6] Menu
    Develpment/Android Using Sample 2020. 9. 13. 21:35

    1. Menu


     menu

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
     
        <item
            android:id="@+id/menu1"
            android:title="menu1"/>
     
        <item
            android:id="@+id/menu2"
            android:title="menu2"/>
     
    </menu>
    cs

    * res/menu : res에 menu 디렉토리를 생성하고, menu 디렉토리에서 Menu Resource File을 추가.

    * 추가하고 싶은 개수 만큼 item을 만들고, id, title 설정.


     Activity

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public class MainActivity extends AppCompatActivity {
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
     
            getMenuInflater().inflate(R.menu.menu, menu);
            return true;
        }
    }
    cs

    * onCreateOptionMenu 를 Override 한다.

    getMenuInflater() 를 호출하여 추가.



    2. 결과화면


     




    3. Menu Click Event


     Activity 

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    public class MainActivity extends AppCompatActivity {
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
     
            getMenuInflater().inflate(R.menu.menu, menu);
            return true;
        }
     
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
     
            switch( item.getItemId() )
            {
                case R.id.menu1:
                    //menu1 Event
                    Toast.makeText(getApplicationContext(), "menu1", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.menu2:
                    //menu2 Event
                    break;
            }
     
            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

    댓글

Designed by Tistory.