Button在AlertDialog中的布局

发布时间:2024-08-31 09:01:51 作者:小樊
来源:亿速云 阅读:82

在Android中,要将Button添加到AlertDialog中,您需要使用setPositiveButton()setNegativeButton()setNeutralButton()方法

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

public class MainActivity extends AppCompatActivity {

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

    public void showAlertDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Alert Dialog")
                .setMessage("This is an example of an Alert Dialog with buttons.")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "OK button clicked", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Cancel button clicked", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("Ignore", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "Ignore button clicked", Toast.LENGTH_SHORT).show();
                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
}

在这个例子中,我们创建了一个带有标题、消息和三个按钮(积极的、消极的和中立的)的AlertDialog。当用户点击其中一个按钮时,将显示一个Toast消息。要显示此对话框,请在XML布局文件中添加一个Button,并将其android:onClick属性设置为showAlertDialog

推荐阅读:
  1. 微信小程序button组件如何自定义样式
  2. 微信小程序按钮组件button怎么使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

button

上一篇:EditText如何优化用户输入体验

下一篇:Button控件的动画播放循环

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》