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

1.Fragment实现底部导航栏

Fragment 表示 FragmentActivity 中的行为或界面的一部分。您可以在一个 Activity 中组合多个片段,从而构建多窗格界面,并在多个 Activity 中重复使用某个片段。您可以将片段视为 Activity 的模块化组成部分,它具有自己的生命周期,能接收自己的输入事件,并且您可以在 Activity 运行时添加或移除片段(这有点像可以在不同 Activity 中重复使用的“子 Activity”)。当您将片段作为 Activity 布局的一部分添加时,其位于 Activity 视图层次结构的某个 ViewGroup 中,并且片段会定义其自己的视图布局。
第一步:创建Fragment视图
Fragment实现底部导航栏,TabLayout实现顶部导航栏,二者相互嵌套完成App基本布局框架_第1张图片
以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: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">

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

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

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

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

    <fragment
        android:id="@+id/navigation_person"
        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: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">
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        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: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: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:android="http://schemas.android.com/apk/res/android">

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

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

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

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

    <item
        android:id="@+id/navigation_person"
        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;
    }
}

你可能感兴趣的:(Android,Android-UI,android,ui)