본문 바로가기
개발공부/Java & 안드로이드

[안드로이드] PopupMenu 사용방법 (더보기 버튼)

by 안스토리 2022. 10. 5.

우측 상단의 더보기 버튼을 클릭하면,

게시글 수정 또는 삭제를 선택할 수 있는 PopupMenu를 구현함.

 

 

PopupMenu 사용방법

 

우선, res/menu/ 위치에 menu.xml 파일을 정의해야함.

그리고 java 파일에는 아래와 같이 PopupMenu를 세팅

 

              // PopupMenu 사용방법 (a Menu in XML를 defining해야 한다)
                // 1. Instantiate a PopupMenu with its constructor, which takes the current application Context and the View to which the menu should be anchored.
                PopupMenu popup = new PopupMenu(getApplicationContext(), v);
                // 2. Use MenuInflater to inflate your menu resource into the Menu object returned by PopupMenu.getMenu().
                MenuInflater inflater = popup.getMenuInflater();
                inflater.inflate(R.menu.menu_board, popup.getMenu());
                // + Handling click events
                // To perform an action when the user selects a menu item,
                // you must implement the PopupMenu.OnMenuItemClickListener interface and register it with your PopupMenu by calling setOnMenuItemclickListener().
                // When the user selects an item, the system calls the onMenuItemClick() callback in your interface.
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if(item.getItemId() == R.id.editBoard){
                            Log.i(TAG, "1번 메뉴 클릭");
                        } else if(item.getItemId() == R.id.deleteBoard){
                            Log.i(TAG, "2번 메뉴 클릭");
                        }
                        return false;
                    }
                });

                // 3. Call PopupMenu.show().
                popup.show();
  1. PopupMenu 객체를 생성합니다. 현재 Context와 View를 인자로 사용.
  2. MenuInflater 객체를 선언하고, Menu 객체를 inflate
  3. PopupMenu 객체의 show() 메서드를 호출

 

| 참조

https://developer.android.com/guide/topics/ui/menus

 

메뉴  |  Android 개발자  |  Android Developers

메뉴 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 메뉴는 수많은 유형의 애플리케이션에서 사용되는 보편적인 사용자 인터페이스 구성요소입니다. 친숙

developer.android.com

https://developer.android.com/guide/topics/resources/menu-resource

 

메뉴 리소스  |  Android 개발자  |  Android Developers

메뉴 리소스 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 메뉴 리소스는 MenuInflater로 확장되는 애플리케이션 메뉴(옵션 메뉴, 컨텍스트 메뉴 또는 하위 메

developer.android.com