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

如何将AppCompatActivity转换为Fragment适配安卓底部导航

将Activity转换为Fragment以适配底部导航

直接把你的HomeActivity改成Fragment即可,以下是转换后的完整代码:

public class HomeFragment extends Fragment {

    TextView tvName, tvEmail;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 加载Fragment对应的布局(直接复用原来的activity_home布局即可)
        View view = inflater.inflate(R.layout.activity_home, container, false);
        
        tvName = view.findViewById(R.id.tvName);
        tvEmail = view.findViewById(R.id.tvEmail);

        ParseUser currentUser = ParseUser.getCurrentUser();
        if(currentUser != null){
            tvName.setText(currentUser.getString("name"));
            tvEmail.setText(currentUser.getEmail());
        }

        // 绑定退出按钮的点击事件(替换成你布局里退出按钮的ID)
        view.findViewById(R.id.btn_logout).setOnClickListener(v -> logout());
        
        return view;
    }

    private void logout() {
        ProgressDialog progress = new ProgressDialog(requireContext());
        progress.setMessage("加载中...");
        progress.show();
        
        ParseUser.logOut();
        Intent intent = new Intent(requireContext(), MainActivity.class);
        startActivity(intent);
        // 结束宿主Activity
        requireActivity().finish();
        
        progress.dismiss();
    }
}

关键修改说明:

  • 继承类从AppCompatActivity换成Fragment
  • 用onCreateView替代onCreate方法,通过LayoutInflater加载布局并返回View实例
  • 所有控件查找必须通过加载后的view对象调用findViewById,不能直接调用
  • 上下文改用requireContext()获取Fragment关联的上下文;结束页面时用requireActivity().finish()关闭宿主Activity
  • 移除原方法的View参数,改用代码绑定点击事件(比布局里的android:onClick更可靠,避免上下文问题)

最后修改你的switch case代码,替换成Fragment实例:

switch(item.getItemId()) {
    case R.id.nav_home:
        selectedfrag = new HomeFragment();
        break;
    // 其他底部导航项的case...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:18:24