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

}

});

}

相关推荐
闲暇部落41 分钟前
‌Kotlin中的?.和!!主要区别
android·开发语言·kotlin
诸神黄昏EX3 小时前
Android 分区相关介绍
android
大白要努力!4 小时前
android 使用SQLiteOpenHelper 如何优化数据库的性能
android·数据库·oracle
Estar.Lee4 小时前
时间操作[取当前北京时间]免费API接口教程
android·网络·后端·网络协议·tcp/ip
Winston Wood4 小时前
Perfetto学习大全
android·性能优化·perfetto
Dnelic-7 小时前
【单元测试】【Android】JUnit 4 和 JUnit 5 的差异记录
android·junit·单元测试·android studio·自学笔记
Eastsea.Chen9 小时前
MTK Android12 user版本MtkLogger
android·framework
长亭外的少年16 小时前
Kotlin 编译失败问题及解决方案:从守护进程到 Gradle 配置
android·开发语言·kotlin
建群新人小猿19 小时前
会员等级经验问题
android·开发语言·前端·javascript·php
1024小神20 小时前
tauri2.0版本开发苹果ios和安卓android应用,环境搭建和最后编译为apk
android·ios·tauri