安卓实现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;

}

});

}

相关推荐
丘狸尾1 分钟前
[cisco 模拟器] ftp服务器配置
android·运维·服务器
van叶~2 小时前
探索未来编程:仓颉语言的优雅设计与无限可能
android·java·数据库·仓颉
Crossoads6 小时前
【汇编语言】端口 —— 「从端口到时间:一文了解CMOS RAM与汇编指令的交汇」
android·java·汇编·深度学习·网络协议·机器学习·汇编语言
li_liuliu7 小时前
Android4.4 在系统中添加自己的System Service
android
C4rpeDime9 小时前
自建MD5解密平台-续
android
鲤籽鲲11 小时前
C# Random 随机数 全面解析
android·java·c#
m0_5485147715 小时前
2024.12.10——攻防世界Web_php_include
android·前端·php
凤邪摩羯15 小时前
Android-性能优化-03-启动优化-启动耗时
android
凤邪摩羯15 小时前
Android-性能优化-02-内存优化-LeakCanary原理解析
android
喀什酱豆腐16 小时前
Handle
android