英文:
How to open a fragment in a Activity(non-AppCompatAcitivity)?
问题
正如标题所述,我想要打开一个位于Activity(非AppCompatActivity)中的Fragment。
代码:
TableFragment fragment = new TableFragment();
fragment.setArguments(bundle);
View view = (View) findViewById(R.id.Example);
Activity activity = (Activity) view.getContext(); // 修改这一行
FragmentManager fragmentManager = activity.getFragmentManager(); // 修改这一行
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.idFragment, fragment);
ft.commit();
错误:引起的原因:
java.lang.ClassCastException: android.app.Application无法转换为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();
错误:要求的类型:androidx.fragment.app.FragmentTransaction 提供的类型:android.app.FragmentTransaction
问题: 如何在一个Activity(非AppCompatActivity)中打开一个Fragment?
英文:
as the title states, i would like to open a Fragment, that is located in an Activity(Non AppCompatActivity)
Code:
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();
Error: Caused by:
java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
Also tried:
Activity activity = (Activity) this;
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
TableFragment fragment = new TableFragment();
ft.replace(R.id.idFragment, fragment);
ft.commit();
Error:
Required type: androidx.fragment.app.FragmentTransaction
Provided: android.app.FragmentTransaction
Question: How can i open a Fragment in an Activity (Non AppCompatActivity) ?
答案1
得分: 0
TableFragment
正在扩展AndroidX版本的Fragment
。托管它的活动需要从AndroidX的FragmentActivity
进行扩展。
AppCompatActivity
也可以实现这一点,但出于某种原因,您不希望使用它。这也没问题,因为您可以自己从FragmentActivity
进行扩展。
如果您不希望这样做,那么您的活动将无法显示TableFragment
。您需要使TableFragment
扩展框架版本的Fragment
,该版本已被弃用。
英文:
TableFragment
is extending the AndroidX edition of Fragment
. The activity that hosts it needs to extend from the AndroidX FragmentActivity
.
AppCompatActivity
does this, but for some reason you do not wish to use it. That is fine, as you could extend from FragmentActivity
yourself.
If you do not wish to do that, then your activity cannot display TableFragment
. You would need to have TableFragment
extend the framework edition of Fragment
, which is deprecated.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论