不知道大家在使用kotlin语言使用toast的时候有没有遇到这样一个异常:
java.lang.NoSuchMethodError: No virtual method getActivity()Landroid/app/Activity; in class Landroid/support/v4/app/Fragment; or its super classes (declaration of ‘android.support.v4.app.Fragment’ appears in /data/app/com.baoming-1/split_lib_dependencies_apk.apk)
而这个异常在activity里面就没问题,在fragment里面就报那个错误!
或许是kotlin还不够成熟吧,我在项目中的处理是在基累封装一个方法,其他类执行的时候直接调用就可以了,不知道大家是不是这样的!
具体方法如下:
BaseActivity: fun isActivityValid(): Boolean { if (getActivity().isFinishing) { return false } else if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) && isActivityDestroyed()) { return false } return true } override fun safeToast(message: String) { if (isActivityValid()) { applicationContext.longToast(message) } } BaseFragment: fun isActivityValid(): Boolean { if (getActivity() == null) { MyLog.e("activity is finished") return false } else if (getActivity().isFinishing) { MyLog.e("activity isFinishing") return false } else if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) && getActivity().isDestroyed) { MyLog.e("activity isDestroyed") return false } return true } fun safeToast(message: String) { if (isActivityValid()) { (this.activity as BaseActivity).safeToast(message) } }
作者:陈bu二
链接:https://www.jianshu.com/p/b76e023f65f1