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

您好,我想从我的片段转移到另一个活动。我几乎尝试了找到的所有解决方案,但是在按下按钮后,我的应用程序立即关闭。我是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;

    }


}


月关宝盒
浏览 68回答 1
1回答

慕尼黑5688855

我从这一行假设:intent = new Intent(GalleryFragment.this.getActivity(), HomeFragment.class);您正在尝试启动Fragment,而不是Activity. 为了转换到另一个Fragment,请将您的替换Intent为:&nbsp;btn.setOnClickListener(new View.OnClickListener() {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onClick(View view) {&nbsp; &nbsp; &nbsp; &nbsp; getFragmentManager()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .beginTransaction()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .replace(...) //Or add, depends on your use case&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .commit();&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java