Fragment实现底部导航栏,TabLayout实现顶部导航栏,二者相互嵌套完成App基本布局框架

深渊向深渊呼唤

1.Fragment实现底部导航栏

Fragment 表示 FragmentActivity 中的行为或界面的一部分。您可以在一个 Activity 中组合多个片段,从而构建多窗格界面,并在多个 Activity 中重复使用某个片段。您可以将片段视为 Activity 的模块化组成部分,它具有自己的生命周期,能接收自己的输入事件,并且您可以在 Activity 运行时添加或移除片段(这有点像可以在不同 Activity 中重复使用的“子 Activity”)。当您将片段作为 Activity 布局的一部分添加时,其位于 Activity 视图层次结构的某个 ViewGroup 中,并且片段会定义其自己的视图布局。
第一步:创建Fragment视图
在这里插入图片描述
以choice包为例,ChoiceFragment用于展示布局,而ChoiceViewModel用于为ChoiceFragment准备初始化展示的数据

public class ChoiceFragment extends Fragment {

    private ChoiceViewModel mViewModel;

    public static ChoiceFragment newInstance() {
        return new ChoiceFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_choice, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(ChoiceViewModel.class);
        // TODO: Use the ViewModel
    }

}
public class ChoiceViewModel extends ViewModel {
    // TODO: Implement the ViewModel
    private MutableLiveData<String> mText;

    public ChoiceViewModel() {
        mText = new MutableLiveData<>();
        mText.setValue("This is home fragment");
    }
    
    public LiveData<String> getText() {
        return mText;
    }
    
}

第二步:在res目录下建立navigation文件,在里面创建mobile_navigation.xml文件,用于集中绑定视图。其中app:startDestination="@+id/navigation_home"是以navigation_home为第一个打开的活动

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:andro
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:
    app:startDestination="@+id/navigation_home">

    <fragment
        android:
        android:name="com.example.buttontest.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:
        android:name="com.example.buttontest.ui.dashboard.DashboardFragment"
        android:label="@string/title_attention"
        tools:layout="@layout/fragment_dashboard" />

    <fragment
        android:
        android:name="com.example.buttontest.ui.notifications.NotificationsFragment"
        android:label="@string/title_vip"
        tools:layout="@layout/fragment_notifications" />

    <fragment
        android:
        android:name="com.example.buttontest.ui.doki.DokiFragment"
        android:label="@string/title_doki"
        tools:layout="@layout/doki_fragment" />

    <fragment
        android:
        android:name="com.example.buttontest.ui.person.PersonFragment"
        android:label="@string/title_person"
        tools:layout="@layout/person_fragment" />

</navigation>

第三步:
1.首先在所要依托的活动中加入fragment布局。BottomNavigationView是底部导航栏所需要用到的控件。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:andro
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:
    android:layout_
    android:layout_>
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:
        android:layout_
        android:layout_
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_
        android:layout_
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

2.在res目录中创建menu文件夹,同时在里面创建bottom_nav_menu.xml文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:andro>

    <item
        android:
        android:icon="@drawable/ic_home_black_24dp"
        android:title="@string/title_home" />

    <item
        android:
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_attention" />

    <item
        android:
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_vip" />

    <item
        android:
        android:icon="@drawable/ic_doki_foreground"
        android:title="@string/title_doki" />

    <item
        android:
        android:icon="@drawable/ic_person_foreground"
        android:title="@string/title_person" />

</menu>

注意:此处所有item的id都需要和fragment的id一一对应相同,以达到顺利绑定的效果,此处有多少个item,底部导航栏就有多少个视图选项
3.在主活动代码中完成绑定

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = 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, R.id.navigation_attention, R.id.navigation_vip,R.id.navigation_doki,R.id.navigation_person)
                .build();//所有需要在底部导航栏显示的fragment都需要在此处进行绑定
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
    }
}

由此就可以实现底部导航栏了

2.Tab页签实现顶部导航栏切换

我们只需要在需要使用Tab页签的那个fragment中绑定新的fragment,即可实现在该界面完成顶部为Tab页签,底部为fragment导航。

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private LikeFragment likeFragment;//引用需要用到的fragment
    private ChoiceFragment choiceFragment;
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
            }
        });
        likeFragment = LikeFragment.newInstance();
        choiceFragment = ChoiceFragment.newInstance();
        getChildFragmentManager().beginTransaction().replace(R.id.linearLayout,choiceFragment).commit();
        TabLayout tabLayout = (TabLayout)root.findViewById(R.id.tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Toast.makeText(getActivity(),tab.getText(),Toast.LENGTH_SHORT).show();
                if (tab.getText().equals("爱看")){
                    getChildFragmentManager().beginTransaction().replace(R.id.linearLayout,likeFragment).commit();
                }
                if (tab.getText().equals("精选")){
                    getChildFragmentManager().beginTransaction().replace(R.id.linearLayout,choiceFragment).commit();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        return root;
    }
}
栏目