亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從片段打開的活動立即關閉

從片段打開的活動立即關閉

月關寶盒 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 關注
  • 90 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號