安卓实现5个底部导航栏切换fragment

步骤,写 5 个 fragment 自定义的类+5个布局文件:

java 复制代码
package com.xmkjsoft.xhgh.fragment;

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;

import com.xmkjsoft.xhgh.R;

public class CartFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_cart, container, false);
    }
}






package com.xmkjsoft.xhgh.fragment;

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;

import com.xmkjsoft.xhgh.R;

public class HomeFragment  extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}




package com.xmkjsoft.xhgh.fragment;

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;

import com.xmkjsoft.xhgh.R;

public class MineFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_mine, container, false);
    }
}




package com.xmkjsoft.xhgh.fragment;

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;

import com.xmkjsoft.xhgh.R;

public class SortFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sort, container, false);
    }
}




package com.xmkjsoft.xhgh.fragment;

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;

import com.xmkjsoft.xhgh.R;

public class VideoFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_video, container, false);
    }
}

布局文件

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <Button
        android:id="@+id/center_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment_cart"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity 和布局文件

java 复制代码
package com.xmkjsoft.xhgh;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

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

import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomnavigation.LabelVisibilityMode;
import com.google.android.material.navigation.NavigationBarView;
import com.xmkjsoft.xhgh.fragment.CartFragment;
import com.xmkjsoft.xhgh.fragment.HomeFragment;
import com.xmkjsoft.xhgh.fragment.MineFragment;
import com.xmkjsoft.xhgh.fragment.SortFragment;
import com.xmkjsoft.xhgh.fragment.VideoFragment;

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView bottomNavigationView;

    private FragmentManager fragmentManager;
    private HomeFragment homeFragment;
    private VideoFragment videoFragment;
    private SortFragment sortFragment;
    private CartFragment cartFragment;
    private MineFragment mineFragment;


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


        bottomNavigationView = findViewById(R.id.bottom_navigation);


        // 获取或创建相应菜单项的 Badge
        BadgeDrawable badge = bottomNavigationView.getOrCreateBadge(R.id.home);
        bottomNavigationView.setLabelVisibilityMode(NavigationBarView.LABEL_VISIBILITY_LABELED);

        // 设置红点的颜色为红色
        badge.setBackgroundColor(ContextCompat.getColor(this, R.color.badge_color));
        // 设置 Badge 上显示的数字
        badge.setNumber(999);
        bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.home) {
                    // 处理 Home 子项点击事件
                    return false;
                } else if (item.getItemId() == R.id.video) {
                    // 处理 Video 子项点击事件
                    return true;
                } else if (item.getItemId() == R.id.sort) {
                    // 处理 Sort 子项点击事件
                    return true;
                } else if (item.getItemId() == R.id.cart) {
                    // 处理 Cart 子项点击事件
                    return true;
                } else if (item.getItemId() == R.id.mine) {
                    // 处理 Mine 子项点击事件
                    return true;
                } else {
                    return false;
                }
            }
        });


        /**禁止长按弹出toast**/
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);

        for (int i = 0; i < menuView.getChildCount(); i++) {
            final View view = menuView.getChildAt(i);
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    // 返回true表示消费了长按事件,不再执行默认的长按行为
                    view.performClick(); // 模拟点击事件
                    return true;
                }
            });
        }



        homeFragment=new HomeFragment();
        videoFragment=new VideoFragment();
        sortFragment=new SortFragment();
        cartFragment=new CartFragment();
        mineFragment=new MineFragment();

        fragmentManager = getSupportFragmentManager();

        // 默认显示 exampleFragment
        fragmentManager.beginTransaction().replace(R.id.home_container, homeFragment).commit();


        // 设置底部导航栏的监听器
        bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                if (item.getItemId() == R.id.home) {

                    Fragment fragment2 = fragmentManager.findFragmentById(R.id.video_container);
                    Fragment fragment3 = fragmentManager.findFragmentById(R.id.sort_container);
                    Fragment fragment4 = fragmentManager.findFragmentById(R.id.cart_container);
                    Fragment fragment5 = fragmentManager.findFragmentById(R.id.mine_container);
                    if (fragment2 != null) {
                        fragmentTransaction.remove(fragment2);
                    }
                    if (fragment3 != null) {
                        fragmentTransaction.remove(fragment3);
                    }
                    if (fragment4 != null) {
                        fragmentTransaction.remove(fragment4);
                    }
                    if (fragment5 != null) {
                        fragmentTransaction.remove(fragment5);
                    }
                    // 替换为 fragment1
                    fragmentTransaction.replace(R.id.home_container, homeFragment);
                    fragmentTransaction.commit();
                    return true;
                }
                else if (item.getItemId() == R.id.video) {
                    Fragment fragment1 = fragmentManager.findFragmentById(R.id.home_container);

                    Fragment fragment3 = fragmentManager.findFragmentById(R.id.sort_container);
                    Fragment fragment4 = fragmentManager.findFragmentById(R.id.cart_container);
                    Fragment fragment5 = fragmentManager.findFragmentById(R.id.mine_container);
                    if (fragment1 != null) {
                        fragmentTransaction.remove(fragment1);
                    }
                    if (fragment3 != null) {
                        fragmentTransaction.remove(fragment3);
                    }
                    if (fragment4 != null) {
                        fragmentTransaction.remove(fragment4);
                    }
                    if (fragment5 != null) {
                        fragmentTransaction.remove(fragment5);
                    }
                    // 替换为 fragment1
                    fragmentTransaction.replace(R.id.video_container,videoFragment);
                    fragmentTransaction.commit();

                    return true;
                }
                else if (item.getItemId() == R.id.sort) {
                    Fragment fragment1 = fragmentManager.findFragmentById(R.id.home_container);
                    Fragment fragment2 = fragmentManager.findFragmentById(R.id.video_container);
                    Fragment fragment4 = fragmentManager.findFragmentById(R.id.cart_container);
                    Fragment fragment5 = fragmentManager.findFragmentById(R.id.mine_container);
                    if (fragment1 != null) {
                        fragmentTransaction.remove(fragment1);
                    }
                    if (fragment2 != null) {
                        fragmentTransaction.remove(fragment2);
                    }
                    if (fragment4 != null) {
                        fragmentTransaction.remove(fragment4);
                    }
                    if (fragment5 != null) {
                        fragmentTransaction.remove(fragment5);
                    }
                    // 替换为 fragment1
                    fragmentTransaction.replace(R.id.sort_container,sortFragment);
                    fragmentTransaction.commit();
                    return true;
                }
                else if (item.getItemId() == R.id.cart) {

                    Fragment fragment1 = fragmentManager.findFragmentById(R.id.home_container);
                    Fragment fragment2 = fragmentManager.findFragmentById(R.id.video_container);
                    Fragment fragment3 = fragmentManager.findFragmentById(R.id.sort_container);
                    Fragment fragment5 = fragmentManager.findFragmentById(R.id.mine_container);
                    if (fragment1 != null) {
                        fragmentTransaction.remove(fragment1);
                    }
                    if (fragment2 != null) {
                        fragmentTransaction.remove(fragment2);
                    }
                    if (fragment3 != null) {
                        fragmentTransaction.remove(fragment3);
                    }
                    if (fragment5 != null) {
                        fragmentTransaction.remove(fragment5);
                    }

                    fragmentTransaction.replace(R.id.cart_container,cartFragment);
                    fragmentTransaction.commit();
                    return true;
                }
                else if (item.getItemId() == R.id.mine) {
                    Fragment fragment1 = fragmentManager.findFragmentById(R.id.home_container);
                    Fragment fragment2 = fragmentManager.findFragmentById(R.id.video_container);
                    Fragment fragment3 = fragmentManager.findFragmentById(R.id.sort_container);
                    Fragment fragment4 = fragmentManager.findFragmentById(R.id.cart_container);
                    if (fragment1 != null) {
                        fragmentTransaction.remove(fragment1);
                    }
                    if (fragment2 != null) {
                        fragmentTransaction.remove(fragment2);
                    }
                    if (fragment3 != null) {
                        fragmentTransaction.remove(fragment3);
                    }
                    if (fragment4 != null) {
                        fragmentTransaction.remove(fragment4);
                    }



                    fragmentTransaction.replace(R.id.mine_container,mineFragment);
                    fragmentTransaction.commit();
                    return true;
                }




                return false;
            }
        });


    }
}

布局文件

XML 复制代码
<?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">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:itemRippleColor="@null"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_navigation_menu" />


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

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

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

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

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




</androidx.constraintlayout.widget.ConstraintLayout>

menu文件 5个tab嘛:

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/home"
        android:icon="@drawable/ic_launcher_background"
        android:title="@string/nav_home_text" />
    <item
        android:id="@+id/video"
        android:icon="@drawable/ic_launcher_background"
        android:title="@string/nav_video_text" />
    <item
        android:id="@+id/sort"
        android:icon="@drawable/ic_launcher_background"
        android:title="@string/nav_sort_text" />

    <item
        android:id="@+id/cart"
        android:icon="@drawable/ic_launcher_background"
        android:title="@string/nav_cart_text" />

    <item
        android:id="@+id/mine"
        android:icon="@drawable/ic_launcher_background"
        android:title="@string/nav_mine_text" />
</menu>

string:

复制代码
<resources>
    <string name="app_name">xhgh</string>
    <string name="nav_home_text">首页</string>
    <string name="nav_video_text">小视频</string>
    <string name="nav_sort_text">分类</string>
    <string name="nav_cart_text">购物车</string>
    <string name="nav_mine_text">我的</string>
</resources>

/**禁止长按弹出toast**/

BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);

for (int i = 0; i < menuView.getChildCount(); i++) {

final View view = menuView.getChildAt(i);

view.setOnLongClickListener(new View.OnLongClickListener() {

@Override

public boolean onLongClick(View v) {

// 返回true表示消费了长按事件,不再执行默认的长按行为

复制代码
view.performClick(); // 模拟点击事件

return true;

}

});

}

相关推荐
数据猎手小k13 分钟前
AndroidLab:一个系统化的Android代理框架,包含操作环境和可复现的基准测试,支持大型语言模型和多模态模型。
android·人工智能·机器学习·语言模型
你的小101 小时前
JavaWeb项目-----博客系统
android
风和先行1 小时前
adb 命令查看设备存储占用情况
android·adb
AaVictory.2 小时前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
似霰3 小时前
安卓智能指针sp、wp、RefBase浅析
android·c++·binder
大风起兮云飞扬丶3 小时前
Android——网络请求
android
干一行,爱一行3 小时前
android camera data -> surface 显示
android
断墨先生3 小时前
uniapp—android原生插件开发(3Android真机调试)
android·uni-app
无极程序员5 小时前
PHP常量
android·ide·android studio
萌面小侠Plus6 小时前
Android笔记(三十三):封装设备性能级别判断工具——低端机还是高端机
android·性能优化·kotlin·工具类·低端机