Измените кнопки диалога на «Очистить» с помощью эффекта ряби в styles.xml - PullRequest
0 голосов
/ 02 мая 2019

У меня есть простое диалоговое окно с двумя кнопками, «Позитивное» и «Негативное», которое использует простую компоновку стилей, которую я определил в файле styles.xml.Я хочу, чтобы кнопка отмены имела четкий фон, но при этом при прикосновении к ней оставляла обратную связь с пользователем (например, эффект ряби красного цвета).Я пытался в течение 2 дней и не повезло.Любой вклад был бы великолепен.

Работа с эффектом ряби:

enter image description here

Мой код для следующего макета, который дает макету четкий фон для отмены, но нетВолновой эффект.Но я получаю эффект ряби для Да:

 <style name="AlertDialogThemeTesting" parent="Theme.AppCompat.Dialog.Alert">
    <item name="colorControlHighlight">@color/Red</item>
    <item name="colorControlActivated">@color/Red</item>
    <item name="colorControlNormal">@color/Red</item>
    <item name="android:textColor">@color/Black</item>
    <item name="android:textColorPrimary">@color/Gray</item>
    <item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">@color/Black</item>
    <item name="android:background">?attr/selectableItemBackgroundBorderless</item>
    <item name="backgroundTint">@color/Clear</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">@color/Black</item>
    <item name="android:background">?attr/selectableItemBackgroundBorderless</item>
    <item name="android:backgroundTint">@color/Gold</item>
</style>

Чистый фон, но без эффекта ряби:

enter image description here

Кажетсянапример, добавление прозрачного / белого фона по ряду причин устраняет эффект ряби.

Код для диалога:

final AlertDialog.Builder alert = new AlertDialog.Builder(PopOut.this,
        R.style.AlertDialogTheme);
alert   .setTitle("Delete Profile?")
        .setMessage("Are you sure you want to delete" + profile)
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,
                                        int whichButton)
                    {
                        finish();
                        dialog.dismiss();
                    }
                })
        .setNegativeButton("Cancel", null);

final AlertDialog dialog = alert.create();
dialog.show();

1 Ответ

1 голос
/ 03 мая 2019

Определите кнопку , как показано ниже,

<LinearLayout

    android:id="@+id/test_btn"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginTop="68dp"
    android:background="@drawable/button_effect"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_editor_absoluteX="0dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:fontFamily="@font/titilliumweb_bold"
        android:gravity="center"
        android:text="Test Button"
        android:textColor="@color/UcabWhite" />

</LinearLayout>

создайте button_effect.xml в классе рисования, как показано ниже,

   <ripple xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="@color/colorPrimary"     //colour you want the effect
     android:exitFadeDuration="@android:integer/config_shortAnimTime">
       <selector>
          <item>
             <color android:color="@android:color/transparent" />
          </item>
      </selector>
   </ripple>

Вв то же время определите setOnClickListner для кнопки в вашей активности или Dialog .

test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

, которую я протестировалэто и работает как шарм.Попробуйте и дайте мне знать, если у вас возникнут какие-либо трудности.

РЕДАКТИРОВАТЬ

Определите диалог оповещения, как показано ниже.При длительном нажатии на кнопку отмены вы можете увидеть эффект ряби.Но когда вы просто щелкаете по нему, нет времени показывать эффект как предупреждение, отклоняемое.

 final AlertDialog.Builder alert = new AlertDialog.Builder(this, R.style.AppTheme);
    alert.setTitle("Delete Profile?")
            .setMessage("Are you sure you want to delete")
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton) {
                            finish();
                            dialog.dismiss();
                        }
                    })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    final AlertDialog dialog = alert.create();
    dialog.show();

    Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
    negativeButton.setBackgroundResource(R.drawable.button_mini_oval);

Это поможет.

...