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

}

});

}

相关推荐
selt7916 小时前
Redisson之RedissonLock源码完全解析
android·java·javascript
Yao_YongChao6 小时前
Android MVI处理副作用(Side Effect)
android·mvi·mvi副作用
非凡ghost7 小时前
JRiver Media Center(媒体管理软件)
android·学习·智能手机·媒体·软件需求
席卷全城7 小时前
Android 推箱子实现(引流文章)
android
齊家治國平天下8 小时前
Android 14 系统中 Tombstone 深度分析与解决指南
android·crash·系统服务·tombstone·android 14
maycho12310 小时前
MATLAB环境下基于双向长短时记忆网络的时间序列预测探索
android
思成不止于此10 小时前
【MySQL 零基础入门】MySQL 函数精讲(二):日期函数与流程控制函数篇
android·数据库·笔记·sql·学习·mysql
brave_zhao10 小时前
达梦数据库(DM8)支持全文索引功能,但并不直接兼容 MySQL 的 FULLTEXT 索引语法
android·adb
sheji341611 小时前
【开题答辩全过程】以 基于Android的网上订餐系统为例,包含答辩的问题和答案
android
easyboot11 小时前
C#使用SqlSugar操作mysql数据库
android·sqlsugar