安卓实现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 小时前
OpenGL ES 绘制一个三角形(2)
android·安卓·opengl
巽星石2 小时前
【Godot4.3】简单物理模拟之圆粒子碰撞检测
android
printf_8242 小时前
Android 开发每日定时任务
android
音视频牛哥5 小时前
Android平台如何获取CPU占用率和电池电量信息
android·大牛直播sdk·gb28181对接·gb28181动态水印·gb28181文字水印·gb28181图片水印·android动态水印
v(kaic_kaic)10 小时前
基于STM32热力二级管网远程监控系统设计(论文+源码)_kaic
android·数据库·学习·mongodb·微信·目标跟踪·小程序
奋斗音音11 小时前
Android Studio :The emulator process for AVD was killed。
android·ide·android studio
海伟11 小时前
kotlin flow 使用
android·开发语言·kotlin
柴可夫司机i15 小时前
.NET MAUI(.NET Multi-platform App UI)下拉选框控件
android·.net·visual studio·xamarin
zhangphil16 小时前
Android PopupWindow.showAsDropDown报错:BadTokenException: Unable to add window
android
16seo16 小时前
Android使用RecyclerView仿美团分类界面
android·gitee