Using action menus only for specific fragments in Android Wear OS

Wear OS applications does not have classic Android menus, but instead there is action drawer. It is somewhat similar to classic menus, but not exactly. One notable difference is that drawer is global for whole application and not fragment specific. This maybe fine for small application or companion widget, but hardly enough for complete application. So, there is a way to make it work with fragment specific actions. First, don't inflate it in layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.drawer.WearableDrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:background="@color/dark_grey"
        tools:context=".MainActivity"
        tools:deviceIds="wear"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
...
    <androidx.wear.widget.drawer.WearableActionDrawerView
            android:id="@+id/bottom_action_drawer"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</androidx.wear.widget.drawer.WearableDrawerLayout>


Then, enable and inflate it for each fragment with menu like:


    @Override
    public void onResume() {
        super.onResume();
        final Menu menu = mainActivity.wearableActionDrawer.getMenu();
        menu.clear();
        mainActivity.getMenuInflater().inflate(R.menu.sensor_menu, menu);
        mainActivity.wearableActionDrawer.setIsLocked(false);
        mainActivity.wearableActionDrawer.getController().peekDrawer();
        ...
    }


And for each fragment without menu like:


    @Override
    public void onResume() {
        super.onResume();
        mainActivity.wearableActionDrawer.setIsLocked(true);
        mainActivity.wearableActionDrawer.getController().closeDrawer();
        ...
    }

Comments