安卓系统中匿名类的InstantiationException问题



A。我想使用AlertDialogBox Anonymous类创建Popup,如下所示:

private void showPopupChangeCurrency(final CharSequence[] items, final String title){
    ...
        myAlert = new AlertDialogBox() { //This is anonymous class
        @Override
        protected void setButtonRight() {
        ...
        }
    ...
}

B。问题:当改变方向或语言时,我得到了下面的InstantiationExceptionFC问题:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loudlex/com.loudlex.setting.CloudSettings}: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.loudlex.setting.CloudSettings$5: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3195)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3291)
    at android.app.ActivityThread.-wrap16(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1743)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7010)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:731)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:621)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.loudlex.setting.CloudSettings$5: make sure class name exists, is public, and has an empty constructor that is public
    at android.app.Fragment.instantiate(Fragment.java:642)
    at android.app.FragmentState.instantiate(Fragment.java:114)
    at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1873)
    at android.app.FragmentController.restoreAllState(FragmentController.java:122)
    at android.app.Activity.onCreate(Activity.java:1010)
    at com.loudlex.utility.ConfWindow.onCreate(ConfWindow.java:60)
    at com.loudlex.setting.CloudSettings.onCreate(CloudSettings.java:105)
    at android.app.Activity.performCreate(Activity.java:6786)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3148)

C。问题:我想知道是否有任何解决方案可以很好地处理匿名类。

注意。我知道有一些方法可以克服这个问题,例如:使用公共静态嵌套类或分离到顶级类。感谢

您有三种解决方案:

  1. 在单独的类中移动CloudSettings
  2. 将您的内部类更改为public static

    public static class CloudSettings extends DialogFragment
    
  3. 调用myAlert.setRetainInstance(true);

    控制是否在整个"活动"中保留片段实例重新创建(如配置更改)

    参考:http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(布尔值)

相关内容

  • 没有找到相关文章

最新更新