您好,我想从我的片段转移到另一个活动。我几乎尝试了找到的所有解决方案,但是在按下按钮后,我的应用程序立即关闭。我是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();
}
});
添加回答
举报
0/150
提交
取消