안드로이드는 기본적으로 상단에 ActionBar 제공한다.

 

Toolbar를 만들때 기본적인 방법은 

https://developer.android.com/training/appbar/setting-up?hl=ko&authuser=1 

 

앱 바 설정하기  |  Android 개발자  |  Android Developers

앱 바 설정하기 가장 기본적인 형태의 작업 모음은 한쪽에는 활동 제목을 표시하고 다른 쪽에는 더보기 메뉴를 표시합니다. 앱 바는 이렇게 간단한 형태로도 유용한 정보를 사용자에게 제공하

developer.android.com

상위 개발자 문서에서 이해할 수 있다.

예를 들어 다음과 같은 예를 보자.

 

단순 ConstraintLayout

이렇게 되었을 경우 우측 이미지 두개는 View 내 비즈니스 코드(onClickListener)로 처리해야 하며, 좌측 메뉴 버튼은 Toolbar의 기능을 가져오고 싶다.

 

이럴 경우 https://developer.android.com/reference/android/widget/PopupMenu

 

PopupMenu  |  Android Developers

android.net.wifi.hotspot2.omadm

developer.android.com

PopupMenu를 사용해준다.

A PopupMenu displays a Menu in a modal popup window anchored to a View. The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.[설명발췌]

-> 팝업 메뉴는 뷰에 고정된 뷰에 고정된 양식이 정해진 메뉴를 보여준다. 팝업은 만약 그 뷰에 공간이 있다면 그 아래로 보여지거나, 그 공간이 없다면 그 위로 보여진다. 만약 입력기(키패드와같은)가 보여질때 팝업은 그것이 터치 될때까지 오버랩 하지 않는다.

팝업 외의 부분을 터치할 경우 팝업은 사라진다.

 

 

이처럼 툴바에서 찾을 수 있는 기능들을 단순하게 팝업을 사용함으로써 간단하게 쓸 수 있다.

코드는 다음과 같다.

 

optionMenu = findViewById(R.id.memberTabMenuButton)
//memberTabMenuButton : ImageView

optionMenu.setOnClickListener {
    val popup = PopupMenu(this, it)
    val inflater: MenuInflater = popup.menuInflater
    inflater.inflate(R.menu.menu, popup.menu)
    //The int of R.menu.menu is Same as Toobar Layout Setting
    popup.setOnMenuItemClickListener {  menuItem ->
        when(menuItem.itemId){
            R.id.logout -> {
                Log.d("logout", "selected")
            }
        }
        true
    }
    popup.show()
}

 

+ Recent posts