【发布时间】:2020-11-15 21:25:35
【问题描述】:
正如标题所述,我想打开一个位于 Activity(Non AppCompatActivity) 中的 Fragment
代码:
TableFragment fragment = new TableFragment();
fragment.setArguments(bundle);
View view = (View) findViewById(R.id.Example);
AppCompatActivity activity = (AppCompatActivity) view.getContext().getApplicationContext();
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.replace(R.id.idFragment, fragment);
ft.commit();
错误:原因:
java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
也试过了:
Activity activity = (Activity) this;
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
TableFragment fragment = new TableFragment();
ft.replace(R.id.idFragment, fragment);
ft.commit();
错误:
Required type: androidx.fragment.app.FragmentTransaction
Provided: android.app.FragmentTransaction
问题:如何在 Activity 中打开 Fragment(非 AppCompatActivity)?
【问题讨论】:
-
TableFragment正在扩展Fragment的AndroidX 版本。托管它的活动需要从 AndroidXFragmentActivity扩展。AppCompatActivity执行此操作,但您可以自己扩展FragmentActivity。如果您不想这样做,那么您的活动将无法显示TableFragment。 -
你的意思是你的activity扩展了Activity吗?
-
@CommonsWare,谢谢你成功了。转发你的答案
标签: java android xml android-fragments android-activity