溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Button在AlertDialog中的使用

發(fā)布時(shí)間:2024-08-31 14:35:52 來(lái)源:億速云 閱讀:82 作者:小樊 欄目:移動(dòng)開(kāi)發(fā)

在Android開(kāi)發(fā)中,AlertDialog是一個(gè)常用的對(duì)話框組件,它可以讓用戶在不同的選項(xiàng)之間進(jìn)行選擇

import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("選擇操作");
        builder.setMessage("請(qǐng)選擇你想要執(zhí)行的操作:");

        // 設(shè)置按鈕
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "你點(diǎn)擊了確定按鈕", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "你點(diǎn)擊了取消按鈕", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "你點(diǎn)擊了忽略按鈕", Toast.LENGTH_SHORT).show();
            }
        });

        // 顯示對(duì)話框
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
}

在這個(gè)例子中,我們首先創(chuàng)建了一個(gè)AlertDialog.Builder對(duì)象,然后設(shè)置了對(duì)話框的標(biāo)題、消息和按鈕。接著,我們?yōu)槊總€(gè)按鈕設(shè)置了點(diǎn)擊事件監(jiān)聽(tīng)器,當(dāng)用戶點(diǎn)擊按鈕時(shí),會(huì)顯示一個(gè)Toast提示。最后,我們調(diào)用builder.create()方法創(chuàng)建AlertDialog對(duì)象,并調(diào)用show()方法將其顯示出來(lái)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI