欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

2BottomNavigationView+Fragment+ButterKnife实现底部状态栏切换

程序员文章站 2022-06-17 19:06:10
1 MainActivity.java对应的布局文件activity_main

1 MainActivity.java对应的布局文件activity_main

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

    <FrameLayout
        android:id="@+id/main_page_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

<!-- itemIconTint 是被点击的图标时的颜色改变
     itemTextColor是被点击时文字的改变 -->
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/main_navigation_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:itemIconTint="@drawable/navigation_bar_color"
        app:itemTextColor="@drawable/navigation_bar_color"
        app:menu="@menu/my_navigation_items"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

给FrameLayout属性添加id,便于其他fragment替换该部分的内容。
给BottomNavigationView添加id,便于给底部状态栏添加单击监听事件。
2 先抽取Fragment的基类BaseFragment

package com.example.taobaounion.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


public abstract class BaseFragment extends Fragment {
    /**
     *
     * @param inflater 打气筒,加载布局
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //绑定布局,第三个参数:是否绑定到container里面去,false表示不绑定,如果绑定过去就会有问题
        return loadRootView(inflater,container,savedInstanceState);
    }

    protected View loadRootView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        int resId = getRootViewResId();
        return inflater.inflate(resId,container,false);
    }

    protected abstract int getRootViewResId();
}

3 创建四个子类继承BaseFragment

1package com.example.taobaounion.fragment;
import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;

public class HomeFragment extends BaseFragment {
    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home;
    }
}2package com.example.taobaounion.fragment;

import androidx.fragment.app.Fragment;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class RedPacketFragment extends BaseFragment {

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_red_packet;
    }
}3package com.example.taobaounion.fragment;

import androidx.fragment.app.Fragment;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchFragment extends BaseFragment {


    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_search;
    }
}4package com.example.taobaounion.fragment;

import androidx.fragment.app.Fragment;

import com.example.taobaounion.R;
import com.example.taobaounion.base.BaseFragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class SelectedFragment extends BaseFragment {

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_selected;
    }
}

3
(1)使用ButterKnife初始化mBottomNavigationView控件

//在MainActivity.java中
/*1 初始化底部导航栏控件,使用插件butterKnife
    * (1)bind方法绑定
    * (2)使用注解@BindView,注意该注解不可以是私有和静态,因为是通过反射去赋值*/
//第二步
@BindView(R.id.main_navigation_bar)
public BottomNavigationView mBottomNavigationView;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //第一步
        ButterKnife.bind(this);
    }

(2)给底部导航栏添加事件监听

(3)实现主页面的切换

package com.example.taobaounion;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.taobaounion.base.BaseFragment;
import com.example.taobaounion.fragment.HomeFragment;
import com.example.taobaounion.fragment.RedPacketFragment;
import com.example.taobaounion.fragment.SearchFragment;
import com.example.taobaounion.fragment.SelectedFragment;
import com.example.taobaounion.utils.LogUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    /*1 初始化底部导航栏控件,使用插件butterKnife
    * (1)bind方法绑定
    * (2)使用注解@BindView,注意该注解不可以是私有和静态,因为是通过反射去赋值*/
    //抽取成全局变量的快捷键:ctrl+alt+f
    @BindView(R.id.main_navigation_bar)
    public BottomNavigationView mBottomNavigationView;

    private FragmentManager mFm;
    private HomeFragment mHomeFragment;
    private SelectedFragment mSelectedFragment;
    private RedPacketFragment mRedPacketFragment;
    private SearchFragment mSearchFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


        //2 给底部导航栏添加事件监听
        initListener();

        /*
        * 实现主页面的切换*/
        initFragment();

    }

    private void switchFragment(BaseFragment targetFragment) {
        FragmentTransaction fragmentTransaction = mFm.beginTransaction();//开启事务
        fragmentTransaction.replace(R.id.main_page_container,targetFragment); //替换fragment
        fragmentTransaction.commit();//提交事务
    }

    private void initFragment() {
        mHomeFragment = new HomeFragment();
        mSelectedFragment = new SelectedFragment();
        mRedPacketFragment = new RedPacketFragment();
        mSearchFragment = new SearchFragment();

        mFm = getSupportFragmentManager();//拿到一个支持包
        switchFragment(mHomeFragment); //默认选中第一页
    }

    private void initListener() {
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //Log.d(TAG,"title -- > " + item.getTitle());
                if (item.getItemId() == R.id.home){
                    LogUtils.d(MainActivity.class,"切换到首页");
                    switchFragment(mHomeFragment);
                }else if (item.getItemId() == R.id.selected){
                    LogUtils.d(MainActivity.class,"切换到精选");
                    switchFragment(mSelectedFragment);
                }else if (item.getItemId() == R.id.red_packet){
                    LogUtils.d(MainActivity.class,"切换到特惠");
                    switchFragment(mRedPacketFragment);
                }else if (item.getItemId() == R.id.search){
                    LogUtils.d(MainActivity.class,"切换到搜索");
                    switchFragment(mSearchFragment);
                }

                return true;//这里写true,表示我们消费了这个事件
            }
        });
    }


//    private void initView() {
//        HomeFragment homeFragment = new HomeFragment();
//        FragmentManager fm = getSupportFragmentManager();//拿到一个支持包
//        FragmentTransaction transaction = fm.beginTransaction();//开启事务
//        transaction.add(R.id.main_page_container,homeFragment);//将fragment添加进事务中
//        transaction.commit(); //必须提交事务,不然添加Fragment不成功
//
//    }
}

贴上某个Fragment的布局文件,其他三个类似

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="首页"/>

</LinearLayout>

本文地址:https://blog.csdn.net/weixin_44021636/article/details/109962096