화면이 많지 않고 단순한 기능이 필요한데 각자 다른 버튼이 필요하게 되어서 Theme를 NoActionBar로 만들고 각 Fragment에서 Toolbar를 단독으로 사용하기로 했다.
같은 이름을 가진 클래스지만 서로 호환되지 않는 경우가 많고 사용법이나 지원하는 기능도 조금씩 다르다.
특별한 커스텀을 하지 않은 MaterialToolbar를 기준으로 설명한다.
<LinearLayout ...>
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/chatList_toolbar"
android:background="?android:attr/colorPrimary"
android:layout_width="match_parent"
android:layout_height="wrap_conten"
app:menu="@menu/menu_chat_list"
app:navigationIcon="?attr/homeAsUpIndicator"
app:title="@string/chatList_title" />
<TextView ...>
</LinearLayout>
app:menu
를 사용해 res/menu
의 menu를 선택하고 toolbar의 우측에 표시된다.app:navigationIcon
에 아이콘을 등록하면 좌측에 표시된다.app:title
을 toolbar의 가운데에 표시되는 제목을 설정할 수 있다.binding.chatListToolbar.setOnMenuItemClickListener { menuItem: MenuItem ->
when (menuItem.itemId) {
R.id.item_chatList_logout -> {
//클릭 이벤트 내용
true
}
//다른 아이템
else -> false
}
}
//내부 코드
/**
* Set a listener to respond to menu item click events.
*
* <p>This listener will be invoked whenever a user selects a menu item from
* the action buttons presented at the end of the toolbar or the associated overflow.</p>
*
* @param listener Listener to set
*/
public void setOnMenuItemClickListener(OnMenuItemClickListener listener) {
mOnMenuItemClickListener = listener;
}
-----------------
/**
* Interface responsible for receiving menu item click events if the items themselves
* do not have individual item click listeners.
*/
public interface OnMenuItemClickListener {
/**
* This method will be invoked when a menu item is clicked if the item itself did
* not already handle the event.
*
* @param item {@link MenuItem} that was clicked
* @return <code>true</code> if the event was handled, <code>false</code> otherwise.
*/
public boolean onMenuItemClick(MenuItem item);
}
setOnMenuItemClickListener
로 아이템에 따른 이벤트를 등록한다.배토의 개발일지 - Android: App bar 에 대해 (feat. ActionBar, Toolbar)
androidx Toolbar | Android Developers
android Toolbar | Android Developers
Difference Between AppBar, ActionBar, and Toolbar in Android - GeeksforGeeks
MenuItem.OnMenuItemClickListener | Android Developers
스타일 및 테마 | Android 개발자 | Android Developers