Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSupportFragmentManager() undefined in adapter when using AppCompatActivity

I have an activity (MainActivity) which extends AppCompatActivity because I am using some of the material design elements in my app.

I then have an array adapter with a few fields and a button. This adapter has a separate view and is injected into my MainActivity layout.

When I click the button on the adapter view, I want to open a new fragment which displays a bunch of text, however, I can't seem to do this and I think it is because I am not extending FragmentActivity in my MainActivity? I read on another post that I should be able to extend AppCompatActivity and still be able to reference the fragment manager...here is my code to open the fragment:

In my custom array adapter, onClick() of a button:

holder.desc.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
      JobDescFragment fragment= new JobDescFragment();
      FragmentTransaction transaction =      getSupportFragmentManager().beginTransaction();
      transaction.replace(R.id.fragment_container, fragment);
      transaction.addToBackStack(null);  
      transaction.commit();
  }
});

The error I get is that it cannot resolve getSupportFragmentManager(). What am I doing wrong?

I am importing android.support.v4.app.Fragment and .FragmentManager in my adapter.

Thanks in advance for the help!

EDIT:

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <com.lorentzos.flingswipe.SwipeFlingAdapterView
        android:id="@+id/frame"
        android:background="@color/laborswipe_lightgray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:context=".MainActivity"
        android:layout_gravity="top"   />

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</merge>
like image 889
user2573690 Avatar asked Aug 05 '16 02:08

user2573690


2 Answers

you can try this

FragmentTransaction ft = ((AppCompatActivity) mContext).getSupportFragmentManager()
                        .beginTransaction();
like image 58
Jenis Kasundra Avatar answered Oct 09 '22 19:10

Jenis Kasundra


In kotlin it will be like this for example. I have tried it and it work perfectly

val dialog = IntervAddFragment()//The fragment that u want to open for example
       val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
        dialog.show(ft, ContentValues.TAG)
like image 43
DINA TAKLIT Avatar answered Oct 09 '22 19:10

DINA TAKLIT