#android #bottom-sheet #android-navigation #android-bottomnav
#Android #нижняя таблица #android-навигация #android-bottomnav
Вопрос:
Я просто хочу, чтобы мой пункт меню «Еще» открывал BottomSheet
:
Я использую новый навигационный компонент Android с навигационным графиком, но я не могу понять, где я мог бы переопределить поведение.
Мой menu.xml
выглядит так:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@ id/navigation_home_screen"
android:icon="@drawable/ic_add_white_24dp"
android:title="@string/title_home" />
<item
android:id="@ id/navigation_sas"
android:icon="@drawable/ic_check_white_24dp"
android:title="@string/title_activity_sa" />
<item
android:id="@ id/navigation_profile"
android:icon="@drawable/ic_close_white_24dp"
android:title="@string/title_profile" />
<item
android:id="@ id/navigation_more_menu"
android:icon="@drawable/ic_more_horiz_24"
android:title="@string/title_more_menu" />
</menu>
Мой nav-graph
:
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@ id/mobile_navigation"
app:startDestination="@id/navigation_home_screen">
<fragment
android:id="@ id/navigation_home_screen"
android:name="com.dev.solidmind.ui.HomeScreenFragment"
android:label="@string/title_home"
tools:layout="@layout/fragment_home_screen" />
<fragment
android:id="@ id/navigation_sas"
android:name="com.dev.solidmind.ui.SA_Fragment"
android:label="@string/title_activity_sa"
tools:layout="@layout/fragment_sa" />
<fragment
android:id="@ id/navigation_profile"
android:name="com.dev.solidmind.ui.ProfileFragment"
android:label="@string/title_profile"
tools:layout="@layout/fragment_profile" />
<dialog
android:id="@ id/navigation_more_menu"
android:label="@string/title_more_menu" />
</navigation>
Как вы можете видеть, я попытался добавить меню BottomSheet
«Еще» в виде диалогового окна или какого-либо другого элемента, но ничего не работает.
Я добавил все в методы настройки для компонента навигации и подумал, что могу переопределить поведение в addOnDestinationChangedListener
, но он выдает ошибку, потому что пытается перейти к этому пункту меню:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView bottomNavView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home_screen, R.id.navigation_sas, R.id.navigation_profile, R.id.navigation_more_menu)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(bottomNavView, navController);
navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
if (destination.getId() == R.id.navigation_home_screen) {
Objects.requireNonNull(getSupportActionBar()).hide();
} else if (destination.getId() == R.id.navigation_more_menu) {
openBottomSheet();
} else {
Objects.requireNonNull(getSupportActionBar()).show();
}
});
}
openBottomSheet
метод:
public void openBottomSheet() {
View dialogView = getLayoutInflater().inflate(R.layout.main_bottom_sheet_menu, findViewById(R.id.main_root_layout), false);
BottomSheetDialog dialog = new BottomSheetDialog(this);
if (paidContentUnlocked)
adaptBottomSheetToPaidStatus(dialogView);
dialog.setContentView(dialogView);
dialog.show();
}
Могу ли я запретить навигацию и вместо этого открывать только свое меню?
Без необходимости возвращаться к ручному управлению фрагментами с транзакциями и т. Д…
Комментарии:
1. Если это не работает, вы можете попробовать
setOnNavigationItemSelectedListener
на своемbottomNavView
2. @NaveenRao Большое спасибо, это действительно сработало!! Но теперь мне приходится обрабатывать другие случаи вручную с
navController.navigate(R.id.xyz)
помощью или есть какой-то способ вызватьsuper.doSomething()
и не управлять им?3. Я думаю, если вы хотите настроить эти нижние навигационные прослушиватели, то вам нужно сделать
findNavController(R.id.main_container).navigate(fragmentID)
и для других элементов.4. @NaveenRao Если вы хотите, вы можете написать это как ответ, я приму его. Большое спасибо.
5. Нет проблем, все в порядке. Рад вам помочь
Ответ №1:
Я смог это сделать, просто окружив свой <fragment>
тег CoordinatorLayout
символом, как показано ниже
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<fragment
android:id="@ id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph"
android:fillViewport="true"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@ id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_navigation_menu"
app:labelVisibilityMode="labeled"
/>
</LinearLayout>
MyBottomSheet
class BottomSheetFragment: BottomSheetDialogFragment(), View.OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = BottomSheetDialog(requireContext(), theme)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_bottom_sheet, container, false)
}
}
ИЛИ ответ @Naveen Rao
findViewById(R.id.nav_bottom_view).setOnNavigationItemSelectedListener {
// This is to avoid going to startDestination of opening of the BottomSheet
navController.navigate(it.itemId)
true
}