gpt4 book ai didi

java - 尝试在 Android 中打开新屏幕/Activity

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:39 25 4
gpt4 key购买 nike

当用户单击其中一个选项时,我尝试切换到新屏幕。此代码嵌套在主 Activity 中。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_settings:
Log.d("tcc", "This is getting to the about fragment");
startActivity(new Intent(MainActivity.this, HelpFragment.class));
return true;
case R.id.help_settings:
Log.d("tcc", "This is getting to the help fragment");
startActivity(new Intent(MainActivity.this, SettingsFragment.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}

然后我试图让它切换到我创建的 fragment 之一。当我这样做时,我收到一个错误:

Unable to instantiate activity ComponentInfo{info.hccis.bookingapplication/info.hccis.bookingapplication.SettingsFragment}: java.lang.ClassCastException: info.hccis.bookingapplication.SettingsFragment cannot be cast to android.app.Activity

最佳答案

您想要进行 fragment 事务而不是startActivity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (item.getItemId()) {

case R.id.about_settings:
Log.d("tcc", "This is getting to the about fragment");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new HelpFragment());
fragmentTransaction.addToBackStack(null); // to provided navigation when back is clicked
fragmentTransaction.commit();
return true;

case R.id.help_settings:
Log.d("tcc", "This is getting to the help fragment");

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new SettingsFragment());
fragmentTransaction.addToBackStack(null); // to provided navigation when back is clicked
fragmentTransaction.commit();
return true;

default:
return super.onOptionsItemSelected(item);
}
}

And define a fragment coinainer/which will be replaced by your fragments: in your Activity's View:

 <FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">

关于java - 尝试在 Android 中打开新屏幕/Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60162603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com