2.6 通知类控件 Toast、Menu

本文详细介绍了Android中的通知控件Toast及其四种使用方式:默认效果、自定义位置、带图片和完全自定义。同时讲解了OptionMenu、ContextMenu和PopupMenu的使用,包括各自的特点、创建和事件处理。提供了代码示例和布局文件解析,帮助读者深入理解Android菜单与Toast的实现。
摘要由CSDN通过智能技术生成

本文例程下载:WillFlow_ToastWillFlowMenu

一、什么是Toast?

Toast 也被叫做吐司,是 Android 系统提供的一种非常好的提醒方式,在程序中可以使用它将一些短小的信息通知给用户,它有如下两个特点:
- Toast 是没有焦点的
- Toast显示的时间有限过一定的时间就会自动消失
所以一般来讲Toast的使用并不会影响我们的正常操作,并且它通常不会占用太大的屏幕空间,有着良好的用户体验。

使用Toast的一般步骤:

1、调用Toast的构造器或者makeText()静态方法构造一个Toast对象。
2、调用Toast的方法来设置该消息的提醒方式、页边距等。
3、调用Toast的show()方法将它显示出来。

百闻不如一见:

我们现在就尝试一下如何在活动中使用 Toast。

二、Toast的四种使用方式

首先需要定义一个弹出 Toast 的触发点,那我们就在界面上定义几个按钮,当点击这个按钮的时候弹出对应的 Toast 。然后在 onCreate()方法中添加代码:

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

        initView();
    }

    private void initView() {
        mButton1 = (Button) findViewById(R.id.button1);
        mButton2 = (Button) findViewById(R.id.button2);
        mButton3 = (Button) findViewById(R.id.button3);
        mButton4 = (Button) findViewById(R.id.button4);
        mButton1.setOnClickListener(this);
        mButton2.setOnClickListener(this);
        mButton3.setOnClickListener(this);
        mButton4.setOnClickListener(this);
    }

其布局文件activity_main.xml为:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.wgh.willflow_toast.MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:text="默认Toast样式" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:text="自定义显示位置效果" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:text="带图片效果" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:text="完全自定义效果" /><
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值