java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity

谁说我不能喝 提交于 2020-04-18 06:15:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!