You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击BottomSheet内控件打开Fragment、添加返回栈及登出弹窗

实现代码修改说明

1. 重写BottomSheet.java逻辑

你只需要修改BottomSheet.java文件,绑定布局里所有TextView的点击事件即可,完整修改后代码如下:

public class BottomSheet extends BottomSheetDialogFragment {

    public BottomSheet() {
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.bottom_sheet_profile, container, false);
        
        // 绑定所有选项控件
        TextView tvSettings = rootView.findViewById(R.id.settings);
        TextView tvEditProfile = rootView.findViewById(R.id.edit_profile);
        TextView tvFavorite = rootView.findViewById(R.id.favorite);
        TextView tvLogout = rootView.findViewById(R.id.log_out);
        
        // 跳转到设置页
        tvSettings.setOnClickListener(v -> {
            dismiss();
            navigateToFragment(new SettingsFragment());
        });
        
        // 跳转到编辑资料页
        tvEditProfile.setOnClickListener(v -> {
            dismiss();
            navigateToFragment(new EditProfileFragment());
        });
        
        // 跳转到收藏页
        tvFavorite.setOnClickListener(v -> {
            dismiss();
            navigateToFragment(new FavoriteFragment());
        });
        
        // 点击登出弹出确认对话框
        tvLogout.setOnClickListener(v -> {
            dismiss();
            new androidx.appcompat.app.AlertDialog.Builder(requireContext())
                    .setTitle("确认登出")
                    .setMessage("确定要退出当前账号吗?")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 此处补充你的登出业务逻辑,比如清除本地用户数据、跳转到登录页等
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
        
        return rootView;
    }
    
    // 封装跳转Fragment的公共方法,自动添加到返回栈
    private void navigateToFragment(Fragment fragment) {
        requireActivity().getSupportFragmentManager()
                .beginTransaction()
                // 此处R.id.fragment_container替换为你项目里Activity中承载Fragment的容器id
                .replace(R.id.fragment_container, fragment)
                .addToBackStack(null)
                .commit();
    }
}

2. 注意事项

  • 代码里的SettingsFragment、EditProfileFragment、FavoriteFragment替换为你自己项目中对应的Fragment类
  • R.id.fragment_container替换为你宿主Activity布局里用来放Fragment的容器控件id
  • 登出确认框的点击逻辑根据你自己的业务需求补充即可

内容的提问来源于stack exchange,提问作者Vasant Raval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 10:45:00