簡體   English   中英

如何在 Android 上顯示警報對話框?

[英]How do I display an alert dialog on Android?

我想向用戶顯示一個對話框/彈出窗口,其中顯示“您確定要刪除此條目嗎?” 一個按鈕,上面寫着“刪除”。 觸摸Delete時,它​​應該刪除該條目,否則什么也沒有。

我已經為這些按鈕編寫了一個點擊偵聽器,但是如何調用對話框或彈出窗口及其功能?

您可以為此使用AlertDialog並使用其Builder類構造一個。 下面的示例使用默認構造函數,該構造函數僅接受Context因為對話框將從您傳入的 Context 繼承正確的主題,但也有一個構造函數允許您將特定主題資源指定為第二個參數(如果您願意)這樣做。

new AlertDialog.Builder(context)
    .setTitle("Delete entry")
    .setMessage("Are you sure you want to delete this entry?")

    // Specifying a listener allows you to take an action before dismissing the dialog.
    // The dialog is automatically dismissed when a dialog button is clicked.
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // Continue with delete operation
        }
     })

    // A null listener allows the button to dismiss the dialog and take no further action.
    .setNegativeButton(android.R.string.no, null)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();

試試這個代碼:

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);

builder1.setPositiveButton(
    "Yes",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

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

AlertDialog alert11 = builder1.create();
alert11.show();

David Hedlund 發布的代碼給了我錯誤:

無法添加窗口 — 令牌空無效

如果您遇到相同的錯誤,請使用以下代碼。 有用!!

runOnUiThread(new Runnable() {
    @Override
    public void run() {

        if (!isFinishing()){
            new AlertDialog.Builder(YourActivity.this)
              .setTitle("Your Alert")
              .setMessage("Your Message")
              .setCancelable(false)
              .setPositiveButton("ok", new OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      // Whatever...
                  }
              }).show();
        }
    }
});

使用AlertDialog.Builder

AlertDialog alertDialog = new AlertDialog.Builder(this)
//set icon 
 .setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Are you sure to Exit")
//set message
.setMessage("Exiting will call finish() method")
//set positive button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what would happen when positive button is clicked    
        finish();
    }
})
//set negative button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what should happen when negative button is clicked
        Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
    }
})
.show();

您將獲得以下輸出。

安卓警報對話框

要查看警報對話框教程,請使用下面的鏈接。

Android 警報對話框教程

只是一個簡單的! 在 Java 類中的任何位置創建一個對話框方法,如下所示:

public void openDialog() {
    final Dialog dialog = new Dialog(context); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    dialog.show();
}

現在創建布局 XML dialog_demo.xml並創建您的 UI/設計。 這是我為演示目的創建的示例:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/dialog_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/dialog_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/dialog_info">

        <Button
            android:id="@+id/dialog_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_cancel_bgcolor"
            android:text="Cancel"/>

        <Button
            android:id="@+id/dialog_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_ok_bgcolor"
            android:text="Agree"/>
    </LinearLayout>
</RelativeLayout>

現在你可以從你喜歡的任何地方調用openDialog() :) 這是上面代碼的屏幕截圖。

在此處輸入圖片說明

請注意,文本和顏色是從strings.xmlcolors.xml 你可以定義你自己的。

現在最好使用 DialogFragment 而不是直接創建 AlertDialog。

您可以使用此代碼:

AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
    AlertDialogActivity.this);

// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");

// Setting Dialog Message
alertDialog2.setMessage("Are you sure you want delete this file?");

// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);

// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on YES", Toast.LENGTH_SHORT)
                    .show();
        }
    });

// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on NO", Toast.LENGTH_SHORT)
                    .show();
            dialog.cancel();
        }
    });

// Showing Alert Dialog
alertDialog2.show();

為我

new AlertDialog.Builder(this)
    .setTitle("Closing application")
    .setMessage("Are you sure you want to exit?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

          }
     }).setNegativeButton("No", null).show();
// Dialog box

public void dialogBox() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Click on Image for tag");
    alertDialogBuilder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
        }
    });

    alertDialogBuilder.setNegativeButton("cancel",
        new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {

        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}
new AlertDialog.Builder(context)
    .setTitle("title")
    .setMessage("message")
    .setPositiveButton(android.R.string.ok, null)
    .show();

這是如何創建警報對話框的基本示例:

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Dialog on Android");
dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //Action for "Delete".
    }
})
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //Action for "Cancel".
            }
        });

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

在此處輸入圖片說明

這絕對對你有幫助。 試試這個代碼:點擊一個按鈕,你可以放置一個、兩個或三個帶有警報對話框的按鈕......

SingleButtton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with one Button

        AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();

        // Setting Dialog Title
        alertDialog.setTitle("Alert Dialog");

        // Setting Dialog Message
        alertDialog.setMessage("Welcome to Android Application");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.tick);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog,int which)
            {
                // Write your code here to execute after dialog    closed
                Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with two Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Delete...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want delete this?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.delete);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
                    }
                });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,    int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with three Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Save File...");

        // Setting Dialog Message
        alertDialog.setMessage("Do you want to save this file?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.save);

        // Setting Positive Yes Button
        alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on YES",
                            Toast.LENGTH_SHORT).show();
                }
            });

        // Setting Negative No Button... Neutral means in between yes and cancel button
        alertDialog.setNeutralButton("NO",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed No button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on NO", Toast.LENGTH_SHORT)
                            .show();
                }
            });

        // Setting Positive "Cancel" Button
        alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on Cancel",
                            Toast.LENGTH_SHORT).show();
                }
            });
        // Showing Alert Message
        alertDialog.show();
    }
});
showDialog(MainActivity.this, "title", "message", "OK", "Cancel", {...}, {...});

科特林

fun showDialog(context: Context, title: String, msg: String,
               positiveBtnText: String, negativeBtnText: String?,
               positiveBtnClickListener: DialogInterface.OnClickListener,
               negativeBtnClickListener: DialogInterface.OnClickListener?): AlertDialog {
    val builder = AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(msg)
            .setCancelable(true)
            .setPositiveButton(positiveBtnText, positiveBtnClickListener)
    if (negativeBtnText != null)
        builder.setNegativeButton(negativeBtnText, negativeBtnClickListener)
    val alert = builder.create()
    alert.show()
    return alert
}

爪哇

public static AlertDialog showDialog(@NonNull Context context, @NonNull String title, @NonNull String msg,
                                     @NonNull String positiveBtnText, @Nullable String negativeBtnText,
                                     @NonNull DialogInterface.OnClickListener positiveBtnClickListener,
                                     @Nullable DialogInterface.OnClickListener negativeBtnClickListener) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(msg)
            .setCancelable(true)
            .setPositiveButton(positiveBtnText, positiveBtnClickListener);
    if (negativeBtnText != null)
        builder.setNegativeButton(negativeBtnText, negativeBtnClickListener);
    AlertDialog alert = builder.create();
    alert.show();
    return alert;
}

我創建了一個對話框來詢問一個人他是否想打電話給一個人。

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class Firstclass extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.first);

        ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);

        imageViewCall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v)
            {
                try
                {
                    showDialog("0728570527");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    public void showDialog(final String phone) throws Exception
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);

        builder.setMessage("Ring: " + phone);

        builder.setPositiveButton("Ring", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);

                callIntent.setData(Uri.parse("tel:" + phone));

                startActivity(callIntent);

                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });

        builder.show();
    }
}

你可以試試這個....

    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Dialog on Android");
dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //Action for "Delete".
    }
})
        .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            //Action for "Cancel".
            }
        });

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

有關更多信息,請查看此鏈接...

試試這個代碼

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("AlertDialog Title");

    // set dialog message
    alertDialogBuilder
            .setMessage("Some Alert Dialog message.")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(this, "OK button click ", Toast.LENGTH_SHORT).show();

                }
            })
            .setNegativeButton("CANCEL",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                           Toast.makeText(this, "CANCEL button click ", Toast.LENGTH_SHORT).show();

                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

您可以使用AlertDialog.Builder創建對話框

試試這個:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to delete this entry?");

        builder.setPositiveButton("Yes, please", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //perform any action
                Toast.makeText(getApplicationContext(), "Yes clicked", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //perform any action
                Toast.makeText(getApplicationContext(), "No clicked", Toast.LENGTH_SHORT).show();
            }
        });

        //creating alert dialog
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

要更改警報對話框的正負按鈕的顏色,您可以在alertDialog.show();之后編寫以下兩行alertDialog.show();

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

在此處輸入圖片說明

   new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();

當你想關閉對話框時要小心 - 使用dialog.dismiss() 在我的第一次嘗試中,我使用了有時有效的dismissDialog(0) (我可能從某個地方復制了它)。 使用系統提供的對象聽起來是一個更安全的選擇。

我想通過分享比他發布的內容更動態的方法來補充 David Hedlund 的好答案,這樣當您確實需要執行負面操作時可以使用它,而當您沒有執行時,我希望它有所幫助。

private void showAlertDialog(@NonNull Context context, @NonNull String alertDialogTitle, @NonNull String alertDialogMessage, @NonNull String positiveButtonText, @Nullable String negativeButtonText, @NonNull final int positiveAction, @Nullable final Integer negativeAction, @NonNull boolean hasNegativeAction)
{
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(context);
    }
    builder.setTitle(alertDialogTitle)
            .setMessage(alertDialogMessage)
            .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (positiveAction)
                    {
                        case 1:
                            //TODO:Do your positive action here 
                            break;
                    }
                }
            });
            if(hasNegativeAction || negativeAction!=null || negativeButtonText!=null)
            {
            builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (negativeAction)
                    {
                        case 1:
                            //TODO:Do your negative action here
                            break;
                        //TODO: add cases when needed
                    }
                }
            });
            }
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.show();
}

我在按鈕onClick方法中使用了這個AlertDialog

button.setOnClickListener(v -> {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);
    View view = layoutInflaterAndroid.inflate(R.layout.cancel_dialog, null);
    builder.setView(view);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();

    view.findViewById(R.id.yesButton).setOnClickListener(v -> onBackPressed());
    view.findViewById(R.id.nobutton).setOnClickListener(v -> alertDialog.dismiss());
});

對話框.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textmain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:padding="5dp"
    android:text="@string/warning"
    android:textColor="@android:color/black"
    android:textSize="18sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


<TextView
    android:id="@+id/textpart2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:lines="2"
    android:maxLines="2"
    android:padding="5dp"
    android:singleLine="false"
    android:text="@string/dialog_cancel"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textmain" />


<TextView
    android:id="@+id/yesButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="5dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/yes"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textpart2" />


<TextView
    android:id="@+id/nobutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/no"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/yesButton" />


<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:layout_margin="5dp"
    android:padding="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/nobutton" />
</androidx.constraintlayout.widget.ConstraintLayout>

使用材料組件庫,您可以只使用MaterialAlertDialogBuilder

   MaterialAlertDialogBuilder(context)
        .setMessage("Are you sure you want to delete this entry?")
        .setPositiveButton("Delete") { dialog, which ->
            // Respond to positive button press
        }
        .setNegativeButton("Cancel") { dialog, which ->
            // Respond to positive button press
        }   
        .show()

在此處輸入圖片說明

使用Compose 1.0.0-beta03您可以使用:

val openDialog = remember { mutableStateOf(true) }

if (openDialog.value) {
    AlertDialog(
        onDismissRequest = {
            // Dismiss the dialog when the user clicks outside the dialog or on the back
            // button. If you want to disable that functionality, simply use an empty
            // onCloseRequest.
            openDialog.value = false
        },
        title = null,
        text = {
            Text(
                "Are you sure you want to delete this entry?"
            )
        },
        confirmButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                }
            ) {
                Text("Delete")
            }
        },
        dismissButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                }
            ) {
                Text("Cancel")
            }
        }
    )
}

在此處輸入圖片說明

您也可以嘗試這種方式,它會為您提供材質樣式對話框

private void showDialog()
{
    String text2 = "<font color=#212121>Medi Notification</font>";//for custom title color

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>You can complete your profile now or start using the app and come back later</font>";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            toast = Toast.makeText(getApplicationContext(), "DELETE", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();              
        }
    });

    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            toast = Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });
    builder.show();
}
public void showSimpleDialog(View view) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setCancelable(false);
    builder.setTitle("AlertDialog Title");
    builder.setMessage("Simple Dialog Message");
    builder.setPositiveButton("OK!!!", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            //
        }
    })
    .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    // Create the AlertDialog object and return it
    builder.create().show();
}

另請查看我關於 Android 對話框的博客,您將在此處找到所有詳細信息: http : //www.fahmapps.com/2016/09/26/dialogs-in-android-part1/

制作這個靜態方法並在任何你想要的地方使用它。

public static void showAlertDialog(Context context, String title, String message, String posBtnMsg, String negBtnMsg) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setPositiveButton(posBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

        }

Kotln 開發人員最簡單的解決方案

val alertDialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
    alertDialogBuilder.setMessage(msg)
    alertDialogBuilder.setCancelable(true)

    alertDialogBuilder.setPositiveButton(
        getString(android.R.string.ok)
    ) { dialog, _ ->
        dialog.cancel()
    }

    val alertDialog: AlertDialog = alertDialogBuilder.create()
    alertDialog.show()

這是在 kotlin 中完成的

val builder: AlertDialog.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
        } else {
            AlertDialog.Builder(this)
        }
        builder.setTitle("Delete Alert!")
                .setMessage("Are you want to delete this entry?")
                .setPositiveButton("YES") { dialog, which ->

                }
                .setNegativeButton("NO") { dialog, which ->

                }
                .setIcon(R.drawable.ic_launcher_foreground)
                .show()

帶有編輯文本的警報對話框

AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity context
final EditText input = new EditText(context);
builder.setTitle(getString(R.string.remove_item_dialog_title));
        builder.setMessage(getString(R.string.dialog_message_remove_item));
 builder.setTitle(getString(R.string.update_qty));
            builder.setMessage("");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setHint(getString(R.string.enter_qty));
            input.setTextColor(ContextCompat.getColor(context, R.color.textColor));
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            input.setText("String in edit text you want");
            builder.setView(input);
   builder.setPositiveButton(getString(android.R.string.ok),
                (dialog, which) -> {

//Positive button click event
  });

 builder.setNegativeButton(getString(android.R.string.cancel),
                (dialog, which) -> {
//Negative button click event
                });
        AlertDialog dialog = builder.create();
        dialog.show();
import android.app.*;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;

public class ShowPopUp extends Activity {

PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
Button but;
boolean click = true;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    popUp = new PopupWindow(this);
    layout = new LinearLayout(this);
    mainLayout = new LinearLayout(this);
    tv = new TextView(this);
    but = new Button(this);
    but.setText("Click Me");
    but.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            if (click) {
                popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);
                popUp.update(50, 50, 300, 80);
                click = false;
            } else {
                popUp.dismiss();
                click = true;
            }
        }

    });
    params = new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    layout.setOrientation(LinearLayout.VERTICAL);
    tv.setText("Hi this is a sample text for popup window");
    layout.addView(tv, params);
    popUp.setContentView(layout);
    // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
    mainLayout.addView(but, params);
    setContentView(mainLayout);
       }
   }
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("This is Title");
    builder.setMessage("This is message for Alert Dialog");
    builder.setPositiveButton("Positive Button", (dialog, which) -> onBackPressed());
    builder.setNegativeButton("Negative Button", (dialog, which) -> dialog.cancel());
    builder.show();

這是一種類似於使用一些代碼行創建警報對話框的方法。

從列表中刪除條目的代碼

 /*--dialog for delete entry--*/
private void cancelBookingAlert() {
    AlertDialog dialog;
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
    alertDialog.setTitle("Delete Entry");
    alertDialog.setMessage("Are you sure you want to delete this entry?");
    alertDialog.setCancelable(false);

    alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
           //code to delete entry
        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    dialog = alertDialog.create();
    dialog.show();
}

單擊刪除按鈕時調用上述方法

我想顯示一個對話框/彈出窗口,並向用戶顯示“您確定要刪除此條目嗎?”的消息。 一個帶有“刪除”按鈕。 觸摸Delete ,它應刪除該條目,否則不刪除任何條目。

我已經為這些按鈕編寫了一個單擊偵聽器,但是如何調用對話框或彈出窗口及其功能?

     new AlertDialog.Builder(loginregister.this)
            .setTitle("messege")
            .setPositiveButton("ok", null)
            .setMessage( "user name : " + username + "/n" +
                            "password :" + password + "/n"  )
    .show();

Kotlin試試這個

AlertDialog.Builder(this)
            .setTitle("Title")
            .setPositiveButton("Yes"){ dialog, which ->

            }
            .setNegativeButton("No", null)
            .setMessage("Your given alert message...")
            .show()

您可以創建Activity並擴展AppCompatActivity。 然后在清單中放入下一個樣式:

<activity android:name=".YourCustomDialog"
            android:theme="Theme.AppCompat.Light.Dialog">
</activity>

通過Buttons和TextViews對其進行充氣

然后像對話框一樣使用它。

例如,在linearLayout中,我填充下一個參數:

android:layout_width="300dp"
android:layout_height="wrap_content"

在過去的幾天里,我的同事一直問我關於在Xamarin.Android使用AlertDialogXamarin.Android ,幾乎所有的人都將這個問題作為他們在問我之前閱讀的參考(並沒有找到答案)發送,所以這里是Xamarin.AndroidC# )版本:

var alertDialog = new AlertDialog.Builder(this) // this: Activity
    .SetTitle("Hello!")
    .SetMessage("Are you sure?")
    .SetPositiveButton("Ok", (sender, e) => { /* ok things */ })
    .SetNegativeButton("Cancel", (sender, e) => { /* cancel things */ })
    .Create();

alertDialog.Show();

// you can customize your AlertDialog, like so
var tvMessage = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);
tvMessage.TextSize = 13;
// ...
    LayoutInflater inflater = LayoutInflater.from(HistoryActivity.this);
    final View vv = inflater.inflate(R.layout.dialog_processing_tts, null);
    final AlertDialog.Builder alert = new AlertDialog.Builder(
            HistoryActivity.this);
    alert.setTitle("Delete");
    alert.setView(vv);
    alert.setCancelable(false)
            .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    databaseHelperClass.deleteHistory(list.get(position).getID());
                    list.clear();
                    setAdapterForList();

                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

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

Kotlin 自定義對話框:如果您想創建自定義對話框

Dialog(activity!!, R.style.LoadingIndicatorDialogStyle)
        .apply {
            // requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCancelable(true)
            setContentView(R.layout.define_your_custom_view_id_here)

            //access your custom view buttons/editText like below.z
            val createBt = findViewById<TextView>(R.id.clipboard_create_project)
            val cancelBt = findViewById<TextView>(R.id.clipboard_cancel_project)
            val clipboard_et = findViewById<TextView>(R.id.clipboard_et)
            val manualOption =
                findViewById<TextView>(R.id.clipboard_manual_add_project_option)

            //if you want to perform any operation on the button do like this

            createBt.setOnClickListener {
                //handle your button click here
                val enteredData = clipboard_et.text.toString()
                if (enteredData.isEmpty()) {
                    Utils.toast("Enter project details")
                } else {
                    navigateToAddProject(enteredData, true)
                    dismiss()
                }
            }

            cancelBt.setOnClickListener {
                dismiss()
            }
            manualOption.setOnClickListener {
                navigateToAddProject("", false)
                dismiss()
            }
            show()
        }

在 style.xml 中創建 LoadingIndicatorDialogStyle

<style name="LoadingIndicatorDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:statusBarColor">@color/black_transperant</item>
<item name="android:layout_gravity">center</item>
<item name="android:background">@android:color/transparent</item>
<!--<item name="android:windowAnimationStyle">@style/MaterialDialogSheetAnimation</item>-->

現在在 android 中引入了Jetpack Compose ,您可以使用以下代碼簡單地創建警報對話框

if (viewModel.shouldDialogOpen.value) {

        AlertDialog(onDismissRequest = { viewModel.shouldDialogOpen.value = false },
            title = { Text("Delete Entry?") },
            text = {
                Text("Are you sure you want to delete this entry?")
            },
            dismissButton = {
                Button(modifier = Modifier.fillMaxWidth(), onClick = {
                    viewModel.shouldDialogOpen.value = false
                }) {
                    Text(text = "Cancel")
                }
            }, confirmButton = {
                Button(modifier = Modifier.fillMaxWidth(), onClick = {
                    viewModel.shouldDialogOpen.value = false
                    viewModel.beginDelete(recipe)
                }) {
                    Text(text = "Okay")
                }
            })
    }

這里在viewModel.shouldDialogOpenshouldDialogOpen是 viewmodel 中的一個可變狀態字段,當我們需要顯示或關閉對話框時,我們會更改其值。

有關 Jetpack Compose 的更多代碼示例:- https://androidlearnersite.wordpress.com/2021/08/03/jetpack-compose-1-0-0-sample-codes/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM