2017-01-17 20 views
-1

如何在幾個活動中使用我的BottomNavigationView,但沒有在那裏聲明它?如何查看多個活動

我在main_activity.xml中聲明瞭我的Bottom導航視圖,並處理MainActivity類中的點擊邏輯,但是因爲我想在3個活動(地圖,朋友,聊天室)之間切換,我必須有3個Bottomnavigationview底部導航視圖,但由於性能效率低下,我想要在一個類和一個佈局 (MainActivity類和main_activity.xml)中處理所有點擊事件和視圖的初始化。

我該怎麼辦?還是有更好的方法來做到這一點?

回答

1

您應該使用片段而不是活動。只有1個活動,即MainActivity,在BottomNavigationView上添加BottomNavigationView和片段。在點擊BottomNavigationView時,替換碎片。 您的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" 
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> 

從你的活動中,FrameLayout裏添加片段。您的BottomNavigationView將保持不變。只需在單擊NavigationView選項卡上替換此FrameLayout中的片段即可。