Android编程Toast使用,Android中AlertDialog和Toast的使用

本文介绍了Android中的两种常见消息提示框——AlertDialog和Toast的用法。通过实例代码展示了如何创建并响应这两个控件,包括设置标题、消息内容和用户交互。适合初学者理解信息提示框的基本使用。

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

1、AlertDialog是一个信息提示框,当出现是,需要用户点击,才会消失

2、Toast也是一个信息提示框,出现后会更具设定的时间,自动消失

实例代码:

3、布局文件

main.xml

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Make an alert">

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Make a toast">

2、java代码

package yyl.message;

import android.app.Activity;

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 MessageActivity extends Activity {

//定义变量

private Button alert = null;

private Button toast = null;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//根据Id得到控件对象

alert = (Button)findViewById(R.id.alert);

toast = (Button)findViewById(R.id.toast);

//给按钮设定单击事件监听器

alert.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//显示AlertDialog

new AlertDialog.Builder(MessageActivity.this).setTitle("MessageDemo").setMessage("Err").setNeutralButton("close", new DialogInterface.OnClickListener() {

//点击AlertDialog上的按钮的事件处理代码

@Override

public void onClick(DialogInterface dialog, int which) {

System.out.println("yangyulin");

}

}).show();

}

});

toast.setOnClickListener(new View.OnClickListener() {

//显示Toast

@Override

public void onClick(View v) {

Toast.makeText(MessageActivity.this, "", Toast.LENGTH_SHORT).show();

}

});

}

}0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值