问题
I'm trying to setup in my app that is using androidX.
My problem is that when I try to work with PlaceAutocompleteFragment I get errors because it is a fragment from android.app.fragment
and my parent fragment is an androidx fragment: androidx.fragment.app.Fragment
so it uses a androidx.fragment.app.FragmentManager
instead of a android.app.FragmentManager
.
How can I work with "old" fragments in androidX?
回答1:
- Add this to dependencies:
implementation 'androidx.appcompat:appcompat:1.0.2'
. - Add this:
import androidx.fragment.app.FragmentTransaction;
. - Switch your activity extends from
Activity
toAppCompatActivity
. - Change from
getFragmentManager()
togetSupportFragmentManager()
.
This will fix your issue.
回答2:
If you are using the new libraries then only use those, don't combine them bacause yo can run into more problems. Now for your problem go to your fragment and just change the import form:
import android.app.fragment
To:
import androidx.fragment.app.Fragment
That should solve your problem.
回答3:
There is not any need to get the FragmentManager
directly from the Activity
because a replacement method has been provided in the Fragment
called getParentFragmentManager
:
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
From the docs for the deprecated getFragmentManager
:
* @deprecated This has been removed in favor of <code>getParentFragmentManager()</code> which
* throws an {@link IllegalStateException} if the FragmentManager is null. Check if
* {@link #isAdded()} returns <code>false</code> to determine if the FragmentManager is
* <code>null</code>.
The docs for the replacement method getParentFragmentManager
:
* Return the FragmentManager for interacting with fragments associated
* with this fragment's activity. Note that this will available slightly
* before {@link #getActivity()}, during the time from when the fragment is
* placed in a {@link FragmentTransaction} until it is committed and
* attached to its activity.
*
* <p>If this Fragment is a child of another Fragment, the FragmentManager
* returned here will be the parent's {@link #getChildFragmentManager()}.
*
* @throws IllegalStateException if not associated with a transaction or host.
Just take care to check isAdded
to make sure that the FragmentManager
is not null.
来源:https://stackoverflow.com/questions/52256959/fragmentmanager-and-androidx-fragmentmanager