-1

How can I have my BottomNavigationView in several activities but without declaring it there?

i declared my Bottom navigation view in my main_activity.xml and handle the click logic within MainActivity class, but since I want to switch between 3 activities (Map, Friends, Chats) with the Bottomnavigationview i'd have to have 3 bottom navigation views over three activities, but since that's performance inefficient, I want to handle all the click events and initialisation of the view inside one class and one Layout (MainActivity class and main_activity.xml ).

What can I do? or is there a better way of doing this?

4

1 回答 1

1

You should use fragments instead of activities. Have only 1 activity ie MainActivity, add BottomNavigationView and fragments above the BottomNavigationView. And on clicking the BottomNavigationView, replace the fragments. Your XML would be something like,

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<View
    android:id="@+id/bottom_nav_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"/>

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_above="@id/bottom_nav_view"></FrameLayout>

From your activity, add fragments in FrameLayout. Your BottomNavigationView will remain intact. Just replace fragments in this FrameLayout on clicking NavigationView tabs.

于 2017-01-17T19:25:28.437 回答