如何打开 Activity(non-AppCompatAcitivity) 中的片段?

How to open a fragment in a Activity(non-AppCompatAcitivity)?

如标题所述,我想打开一个位于 Activity(Non AppCompatActivity)

中的片段

代码:

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(非 AppCompatActivity)中打开片段?

TableFragment 正在扩展 Fragment 的 AndroidX 版本。承载它的 activity 需要从 AndroidX FragmentActivity.

扩展

AppCompatActivity 这样做,但出于某种原因您不想使用它。很好,因为您可以自己从 FragmentActivity 扩展。

如果您不想这样做,那么您的 activity 将无法显示 TableFragment。您需要 TableFragment 扩展 Fragment 的框架版本,该版本已弃用。