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

Android Alert Dialog Справочная проблема API 11+

Я создаю AlertDialog с кодом ниже. По какой-то причине я получаю дополнительный фон (см. Рис.) На Honeycomb и выше. Код аварийно завершает штраф для чего-либо ниже сотового. MyCustomDialog является просто Theme.Dialog для < API-11 и Theme.Holo.Dialog для API-11 и выше.

  • Любая идея, почему я получаю дополнительный фон?
  • Любая идея, почему она сбой для API < 11? Он отлично работает, если я удаляю тему.

Update выяснил ответ на вопрос №2. Кажется, конструктор AlertDialog.Builder(Context context, int theme) был введен в API 11. Мое решение состояло в том, чтобы просто изменить строку:

final AlertDialog.Builder builder = (Integer.parseInt(android.os.Build.VERSION.SDK) < 11)? new AlertDialog.Builder(this) : new AlertDialog.Builder(this,R.style.JumpDialog);

Мне все еще нужна помощь с вопросом № 1

enter image description here

private Dialog setupKeyBoardDialog() {
    if (mContact.getLocaleId() != -1) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.MyCustomDialog);
        builder.setTitle("Keyboards");

        mKeyboardLayouts = new KeyboardLayoutGroup();
        mKeyboardLayouts.layoutNames = new CharSequence[(int) jni.getNumKeyLayouts()];
        mKeyboardLayouts.layoutValue = new ArrayList<Integer>();

        for (int i = 0; i < jni.getNumKeyLayouts(); i++) {
            mKeyboardLayouts.layoutNames[i] = jni.LayoutInfoForIndex(i).getName();
            mKeyboardLayouts.layoutValue.add(i, (int) jni.LayoutInfoForIndex(i).getLocale_id());
        }

        final int selectedItem = mKeyboardLayouts.layoutValue.indexOf(mContact.getLocaleId());

        builder.setSingleChoiceItems(mKeyboardLayouts.layoutNames, selectedItem, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                mContact.setLocaleId(mKeyboardLayouts.layoutValue.get(item));
                mContactsDB.saveContact(mContact, true);

                dialog.dismiss();
                initializeSettingsList();
            }
        });

        final AlertDialog dialog = builder.create();
        dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogBox, int arg1) {
                dialogBox.cancel();
            }
        });

        return dialog;
    }

    return null;
}
4b9b3361

Ответ 1

Выяснили ответы

  • AlertDialog использует статические константы для каждой темы в AlertDialog, и он не принимает стандартную тему. когда я заменить R.style.MyTheme или android.R.style.Theme_Holo_Dialog с AlertDialog.THEME_HOLO_LIGHT код работал просто хорошо.
  • Кажется, что конструктор AlertDialog.Builder(Context context, int theme) был введен в API 11. Мое решение состояло в том, чтобы просто изменить line to:

    final AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        builder = new AlertDialog.Builder(this);
    } else {
        builder = new AlertDialog.Builder(this,R.style.JumpDialog);
    }
    

Ответ 2

Вы можете использовать new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.JumpDialog)) вместо new AlertDialog.Builder(this, R.style.JumpDialog)

Ответ 3

Для тех, кто ищет способ настроить тему диалога без необходимости придерживаться стандартных (как в принятом решении), начиная с Lollipop, кажется, что дополнительный фон был окончательно удален. Итак, теперь вы можете создать тему, наследующую от стандартного (пример с AppCompat):

<!-- default theme for L devices -->
<style name="SelectionDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:textColor">@color/default_text_color_holo_light</item>
</style>
<!-- theme for Pre-L devices -->
<style name="SelectionDialog.PreL">
    <!-- remove the dialog window background -->
    <item name="android:windowBackground">@color/transparent</item>
</style>

И создайте экземпляр своего создателя с помощью этого кода:

AlertDialog.Builder builder = new AlertDialog.Builder(
            getActivity(),                
            Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT ?
                    R.style.SelectionDialog :
                    R.style.SelectionDialog_PreL);

Конечно, это также можно сделать с папками ресурсов (values/ и values-v21/).