#android #android-bottomappbar
#Android #android-нижняя панель приложений
Вопрос:
Я пытаюсь реализовать нижнюю панель приложений в своем приложении для Android.
MainActivity XML выглядит следующим образом:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@ id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:id="@ id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
app:defaultNavHost="true"
app:navGraph="@navigation/mobile_navigation" />
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:id="@ id/coordinator"
android:layout_height="match_parent">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@ id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@drawable/rpurple"
android:backgroundTint="@color/reallyDarkPurple"
style="@style/Widget.MaterialComponents.BottomAppBar.PrimarySurface"
app:menu="@menu/bottom_nav_menu"
app:tint = "@color/white"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@ id/navigation_profile"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/user"
android:padding="5dp"
app:tint = "@color/lightPurple"
android:scaleType="centerCrop"
android:background="@android:color/transparent"
android:adjustViewBounds="true"/>
<ImageButton
android:id="@ id/historyBtn"
android:layout_width="60dp"
android:padding="5dp"
android:layout_marginEnd="10dp"
android:layout_height="60dp"
android:src="@drawable/clock"
android:layout_alignParentEnd="true"
app:tint = "@color/lightPurple"
android:scaleType="centerCrop"
android:background="@android:color/transparent"
android:adjustViewBounds="true"/>
</RelativeLayout>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="56dp"
android:layout_height="56dp"
android:backgroundTint="@color/lightPurple"
app:srcCompat="@drawable/addwhite"
app:tint = "@color/white"
app:borderWidth="0dp"
android:adjustViewBounds="true"
app:fabCustomSize="56dp"
app:layout_anchor="@id/bottomAppBar"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
И я реализовал такой код в рамках моей MainActivity:
BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.replaceMenu(R.menu.bottom_nav_menu);
setSupportActionBar(bottomAppBar);
В идеале то, что я хотел бы сделать, это перемещаться между 4 отдельными фрагментами, A, B, C, D, используя ImageButtons нижней R.id.navigation_profile
панели приложений, и R.id.historyBtn
ключевой частью требования является то, что кнопки находятся на противоположных сторонах экрана.
Как я мог бы обработать OnClick
для каждого ImageButton, а затем последующий переход фрагмента?
Комментарии:
1. вы хотите добавить навигацию с 4 фрагментами в нижнюю панель приложений?
2. Да, используя два изображения кнопок в XML
Ответ №1:
Насколько я понимаю, вы хотите добавить навигацию с 4 фрагментами в нижнюю панель приложений. Вы можете сделать это, удалив относительный макет в нижней панели приложений и включив его в качестве элемента в меню, подобное этому
сначала добавьте это к зависимостям
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
implementation 'com.google.android.material:material:1.2.1'
ваша основная деятельность
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<FrameLayout
android:id="@ id/hostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#009FFF"
app:layout_anchor="@id/bottomAppBar"
app:maxImageSize="35dp"/>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@ id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabAlignmentMode="center"
android:backgroundTint="#3498DB"
app:fabCradleVerticalOffset="10dp"
app:fabCradleMargin="8dp"
app:hideOnScroll="true"
app:fabCradleRoundedCornerRadius="20dp"
app:menu="@menu/menu"
style="@style/Widget.MaterialComponents.BottomAppBar"
android:theme="@style/AppThemeMaterial"
>
</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
и файл меню должен выглядеть примерно так
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@ id/menu_home"
android:title="Home"
app:showAsAction="always" />
<item
android:id="@ id/menu_message"
android:title="Message"
app:showAsAction="always" />
</menu>
добавьте это в файл стиля
<style name="AppThemeMaterial"
parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
вы можете обрабатывать элемент внизу таким образом
BottomAppBar bottomAppBar=findViewById(R.id.bottomAppBar) ;
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Fragment itemSelected = null ;
switch (item.getItemId()){
case R.id.menu_home:
itemSelected=new Home();
break;
case R.id.menu_message:
itemSelected=new Message();
break;
} getSupportFragmentManager().beginTransaction().replace(R.id.hostFragment,itemSelected).commit();
return true;
}
и вы можете использовать это, чтобы решить, какой фрагмент будет отображаться при открытии введенного действия
onCreate
getSupportFragmentManager().beginTransaction().replace(R.id.hostFragment,
new Home()).commit();
Ответ №2:
В Kotlin мы также можем это сделать
private lateinit var bottomNavigationView: BottomNavigationView
bottomNavigationView = binding.bottomNavView!!
bottomNavigationView.setOnItemReselectedListener {
when (it.itemId) {
R.id.navigation_play-> startGame()
}
}
это даст вам результат, но двумя щелчками мыши…
Немного по-другому (одним щелчком мыши)
bottomNavigationView.setOnItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_play-> startGame()
}
true
}