Подтвердить что ты не робот

Исправление моментации при изменении ориентации При нажатии на DialogFragment вверху

У меня есть DialogFragment, который определяется как внутренний класс в моем классе Fragment. При изменении ориентации появляется даже следующее исключение:

 Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment my.package.fragments.ImportFragment$FailedImportDialog: make sure class name exists, is public, and has an empty constructor that is public
        at android.app.Fragment.instantiate(Fragment.java:585)
        at android.app.FragmentState.instantiate(Fragment.java:96)
        at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1682)
        at android.app.Activity.onCreate(Activity.java:861)
        at my.package.activities.ImportActivity.onCreate(ImportActivity.java:8)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
        ... 12 more
        Caused by: java.lang.InstantiationException: can't instantiate class my.package.fragments.ImportFragment$FailedImportDialog; no empty constructor
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1319)
        at android.app.Fragment.instantiate(Fragment.java:574)

Но у меня есть открытый конструктор:

class FailedImportDialog extends DialogFragment {

        private EditText edtPassword;
        private Button button;

        public FailedImportDialog() { // Here it is!
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.another_password_dialog, container, false);
            edtPassword = (EditText) v.findViewById(R.id.another_password_dialog_et_password);

            getDialog().setTitle(R.string.failed_to_decrypt);

            Button button = (Button) v.findViewById(R.id.another_password_dialog_btn_ok);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

            });

            return v;

    }
}

Вот xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical"
              android:padding="10dp">

    <TextView android:id="@+id/another_password_dialog_tv_text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="@string/what_password_did_you_use">
    </TextView>

    <EditText android:id="@+id/another_password_dialog_et_password"
              android:layout_height="wrap_content"
              android:layout_width="match_parent"
              android:inputType="textPassword">
        <requestFocus>
        </requestFocus>
    </EditText>

    <Button android:id="@+id/another_password_dialog_btn_ok"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="OK">
    </Button>

</LinearLayout>

Вы, ребята, знаете, почему это исключение происходит? Спасибо!

ОБНОВЛЕНИЕ: Если я переведу класс в отдельный файл, такого исключения нет, все идет гладко. Поэтому возникает вопрос: почему это исключение происходит, когда DialogFragment является внутренним классом?

4b9b3361

Ответ 1

попробуйте сделать внутренний класс static:

public static class FailedImportDialog extends DialogFragment 

Я расскажу об этом немного позже. Тем временем попробуйте это и сообщите мне, если это сработает.

Ответ 2

Вызов setRetainInstance (true) приведет к тому, что FragmentManager сохранит ваш фактический экземпляр фрагмента. Вместо того, чтобы уничтожать и воссоздавать Фрагмент, он просто передает одно и то же с новой Деятельностью.

Ответ 3

Определите свой внутренний класс следующим образом:

public class FailedImportDialog extends DialogFragment {
....
}

С публичным обозначением.

Потому что это то, что говорит ваш LogCat:

Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment
my.package.fragments.ImportFragment$FailedImportDialog: make sure class name exists 
is public, and has an empty constructor that is public