问题
I have a problem regarding adapter in fragment. It throws a typo shown below.
java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
Here is the code snippet.
SongDetailFragment fragment =
SongDetailFragment.newInstance(selectedSong);
AppCompatActivity activity = (AppCompatActivity) view.getContext().getApplicationContext();
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.song_detail_container, fragment)
.addToBackStack(null)
.commit();
How can I fix it?
回答1:
In your Fragment use:
AppCompatActivity activity = (AppCompatActivity) getActivity();
instead of:
AppCompatActivity activity = (AppCompatActivity) view.getContext().getApplicationContext();
来源:https://stackoverflow.com/questions/57962537/java-lang-classcastexception-android-app-application-cannot-be-cast-to-androidx