Search code examples
javaandroidxmlandroid-fragmentsandroid-activity

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


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) ?


Solution

  • 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.