Android学习笔记之AlertDialog

本文介绍如何使用Android中的AlertDialog组件,包括创建对话框、设置标题、消息和按钮等操作,并提供了一个完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<1>简介

AlterDialog是一个子类的对话框,可以显示一个,两个或三个按钮。 通过点击对话框显示出的按钮可以触发相应的事件,并且对话框中可以显示你设定的提示Message。

如果你只想显示一个字符串在这个对话框,使用setMessage()方法。

<2>步骤

1、获得AlertDialog静态内部类Buidler对象,由该类来创建AlertDialog对象,因为AlertDialog的构造方法全部是Protected类型
2、通过Buidler对象设置对话框的标题、按钮以及按钮要响应的事件DialogInterface.OnClickListener
3、调用Buidler的create()方法创建对话框
4、调用AlterDialog的show()方法将内容显示出来

<3>范例

package xiaosi.alertDialog; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AlertDialogActivity extends Activity { private Button button = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.Button); button.setOnClickListener(new ButtonListener()); } private class ButtonListener implements OnClickListener{ public void onClick(View v) { showDialog(AlertDialogActivity.this); } } private void showDialog(Context context){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.a); builder.setTitle("提示"); builder.setMessage("你确定要播放吗?"); builder.setPositiveButton("是", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub setTitle("是"); } }); builder.setNeutralButton("否",new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { setTitle("否"); } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { setTitle("取消"); } }); builder.show(); } }


main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id ="@+id/Button" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="点击"/> </LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值