为了账号安全,请及时绑定邮箱和手机立即绑定

从片段打开的活动立即关闭

从片段打开的活动立即关闭

月关宝盒 2023-11-01 20:58:05
您好,我想从我的片段转移到另一个活动。我几乎尝试了找到的所有解决方案,但是在按下按钮后,我的应用程序立即关闭。我是java新手,我想我需要一些帮助。public class GalleryFragment extends Fragment {    private GalleryViewModel galleryViewModel;    Intent intent;    public View onCreateView(@NonNull LayoutInflater inflater,                             ViewGroup container, Bundle savedInstanceState) {        View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);        intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);        final Button btn = (Button) rootView.findViewById(R.id.btn);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                startActivity(intent);            }        });        galleryViewModel =                ViewModelProviders.of(this).get(GalleryViewModel.class);        View root = inflater.inflate(R.layout.fragment_gallery, container, false);        final TextView textView = root.findViewById(R.id.text_gallery);        galleryViewModel.getText().observe(this, new Observer<String>() {            @Override            public void onChanged(@Nullable String s) {                textView.setText(s);            }        });        return root;    }}
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

我从这一行假设:


intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);

您正在尝试启动Fragment,而不是Activity. 为了转换到另一个Fragment,请将您的替换Intent为:


 btn.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

        getFragmentManager()

            .beginTransaction()

            .replace(...) //Or add, depends on your use case

            .commit();

    }

});


查看完整回答
反对 回复 2023-11-01
  • 1 回答
  • 0 关注
  • 45 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信