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

Диалог не показывает положительную и отрицательную кнопку

Я использовал AlertDialog, чтобы предупредить пользователя о подтверждении удаления. Я проверяю свое устройство (Android 5.1), и он хорошо показывает

enter image description here

Но на каком-то другом устройстве (также работает Android 5.1), диалог пропустил положительную и отрицательную кнопку.

enter image description here

Я проверил и обнаружил, что устройства имеют эту проблему со средним разрешением (960x540, 854x480).

Резолюция относится к этой проблеме? Если нет, можете ли вы рассказать мне причину и как исправить эту проблему?

Мой код для отображения:

    public static final Dialog yesNoDialog(Context context,
                                               String message,
                                               DialogInterface.OnClickListener yesAction, DialogInterface.OnClickListener noAction) {


            AlertDialog.Builder  builder = new AlertDialog.Builder(context,R.style.todoDialogLight);

            builder.setTitle(context.getString(R.string.app_name))
                    .setMessage(message)
                    .setCancelable(false)
                    .setPositiveButton("YES", yesAction)
                    .setNegativeButton("NO", noAction);
            return builder.create();
 }

И styles.xml

  <style name="todoDialogLight" parent="Theme.AppCompat.Light.Dialog">

            <!-- Used for the buttons -->
            <item name="colorAccent">@color/colorPrimaryDark</item>
            <item name="android:textStyle">bold</item>
            <!-- Used for the title and text -->
            <item name="android:textColorPrimary">@color/colorText</item>
            <!-- Used for the background -->
            <!-- <item name="android:background">#4CAF50</item>-->
            <item name="android:fontFamily">sans-serif</item>
            <item      name="android:windowAnimationStyle">@style/RemindDialogAnimation</item>
            <item name="android:layout_width">@dimen/width_remind_dialog</item>
            <item name="android:layout_height">wrap_content</item>
 </style>
4b9b3361

Ответ 1

Так что кнопки для меня. К сожалению, они были белым текстом на белом фоне. Это не имеет никакого отношения к разрешению, но больше относится к теме, которую вы выбираете. Чтобы решить эту проблему, вам нужно установить правильный цвет текста в теме диалога.

Например, в styles.xml add

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorPrimary">@color/colorPrimaryDarkBlue</item>
</style>

и в вашей деятельности добавьте

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MyActivity.this, R.style.MyDialogTheme);

Надеюсь это поможет.

Ответ 2

Добавьте это в style.xml:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="android:textColor">@color/colorAccent</item>
</style>

и в использовании деятельности

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MyActivity.this, R.style.MyDialogTheme);

Ответ 3

Решение Али для меня работало. Мой исходный код работал над предыдущими версиями Android версии 7. Но тестирование на моем Pixel давало невидимые кнопки. Я добавил концепцию стиля, подробно описанную Али, как показано ниже, и все хорошо:

   return new AlertDialog.Builder(getActivity(),R.style.MyDialogTheme)
            .setView(v)
            .setTitle(R.string.filter_picker_title)
            .setPositiveButton(android.R.string.ok,
                    // when the user presses the button to select a new number
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            Integer markerIndex = mNumberPicker.getValue();
                            stringFilter=uniqueValues[markerIndex];
                            sendResult(Activity.RESULT_OK,  stringFilter);
                        }
                    })
            .create();

Ответ 4

Если вы используете настраиваемую тему в вашем стиле styles.xml установите цвет colorAccent для более темного цвета.

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimary</item>
        <item name="colorAccent">@color/colorPrimary</item>
    </style>

Ответ 5

Это действительно относится к разрешению, я не знаю точную причину и просто делаю условие if else, чтобы исправить эту проблему.

public static String getDensity(Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        if (density >= 4.0) {
            return "xxxhdpi";
        }
        if (density >= 3.0) {
            return "xxhdpi";
        }
        if (density >= 2.0) {
            return "xhdpi";
        }
        if (density >= 1.5) {
            return "hdpi";
        }
        if (density >= 1.0) {
            return "mdpi";
        }
        return "ldpi";
}

AlertDialog

    public static Dialog yesNoDialog(final Context context,
                                               final String message,
                                               final DialogInterface.OnClickListener yesAction,
                                               final DialogInterface.OnClickListener noAction) {
            int theme = PreferenceUtil.getThemeSetting(context, PreferenceUtil.PREF_THEME);
            AlertDialog.Builder builder = null;
            String density = AppUtil.getDensity(context);
            if (theme == ThemeUtil.THEME_LIGHT) {
                if(density.equals("hdpi")){
                    builder = new AlertDialog.Builder(context);
                }else{
                    builder = new AlertDialog.Builder(context, R.style.todoDialogLight);
                }
            } else {
                if(density.equals("hdpi")){
                    builder = new AlertDialog.Builder(context);
                }else{
                    builder = new AlertDialog.Builder(context, R.style.todoDialogDark);
                }
            }
            builder.setTitle(context.getString(R.string.app_name))
                    .setMessage(message)
                    .setCancelable(false)
                    .setPositiveButton("YES", yesAction)
                    .setNegativeButton("NO", noAction);
            return builder.create();
   }

Надеюсь, что это поможет другим разработчикам, у которых такая же проблема.

Ответ 6

Диалоговое окно диалога;

public void startAlertDialog(String message)
{
    AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);


    alertDialog.setCancelable(false);

    LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
    View view=inflater.inflate(R.layout.alertdialoglayout,null);
    TextViewRagular textViewRagular=(TextViewRagular)view.findViewById(R.id.textviewMessage);
    textViewRagular.setText(message);
    alertDialog.setView(view);
    dialog=alertDialog.create();
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.show();
}

Ответ 7

Перейдите на colors.xml и измените свой colorAccent с этого:

<color name="colorAccent">#FFFFFF</color>

на это:

<color name="colorAccent">#FF4081</color>

Ответ 8

Мы можем установить цвет для кнопок.

public  void showImageDownloadDailog(Activity activity, String message)
{
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setMessage(message);
    builder.setCancelable(false);
    builder.setPositiveButton(
            "Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                   //TODO
                }
            });

    builder.setNegativeButton(
            "No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    //TODO
              }
            });

    AlertDialog alert = builder.create();
    alert.setOnShowListener(arg0 -> {
        alert.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.button_color));
        alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.button_color));
    });
    alert.show();
}