Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

前言

  啦啦啦~又要和大家一起学习Android开发啦,博主心里好激动哒~

  在上篇博文中,我们通过线性布局和基础组件的使用,完成了一个简单的学生课外体育积分电子认证系统的界面,本篇博文,将和大家一起熟悉Button、RadioButton、EditText等基本控件,探讨能够处理这些控件的基本事件,学会弹出基本的对话框,能够定制对话框中的内容,能对确定和取消按钮的事件做处理。

 

基础知识

 

1、在 java 文件中引用布局文件中的控件

  在上一次实验中,在onCreateView(Bundle savedInstanceState) 方法中调用 setContentView()方法将布局加载进来。如果需要用到布局中的某些控件的话,首先需要给控件一个 id:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  定义 id 的语法和引用资源类似,@+id/id 名称,在同一个布局文件中不允许有重复的 id, 即使是不同控件也不行,但是不同的布局文件中可以使用同一个 id之后在 java 文件中将布局加载之后,也就是 setContentView()之后,使用 findViewById() 方法可以获得该控件:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

   findViewById()方法带一个参数,就是刚刚定义的那个 id,参数形式为 R.id.XXX,其中 XXX 就是刚刚定义的那个 id,由于 findViewById()方法返回的是一个 View 类型,所以需要 强制类型转换为 Button 类型。

   获得这个 Button 之后,就可以对这个 Button 进行后续的操作了。 

 

2、弹出 Toast 信息

Toast在APP开发中会经常用到,自己在开发测试中也会用到,测试在还会Logcat窗口显示。 


Toast的主要方法: 
cancel 方法:关闭Toast视图 
getDuration 方法:获取持续时间 
getGravity 方法:获取Toast视图的位置 
makeText 方法:生成标准Toast 
setView 方法:设置显示的View物件 
getView 方法:获取View对象 
setGravity 方法:设置显示位置 
getXOffset 方法:获取水平方向偏移量 
getYOffset 方法:获取垂直方向偏移量 
setDuration 方法:设置持续时间 
setText 方法:设置显示的文本內容 
show 方法:显示提示

在需要弹出 Toast 信息的地方,写上:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  这个方法带三个参数,context,text,duration。context 是一个上下文类型,写上使用 这个方法的 java 类名加上.this 即可,text 是 Toast 要显示的信息,duration 是 Toast 显 示的时间长度,有 Toast.LENGTH_SHORT 和 Toast.LENGTH_LONG 可选,最后记得调用 show() 方法将 Toast 显示出来。

主要包含3种形式的Toast: 
1、标准形式 
2、设置位置形式 
3、带图片的Toast

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

函数代码如下:

MainActivity .java

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)
import java.io.InputStream;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class MainActivity extends Activity {
    Toast   toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //初始化Toast的主要作用是,在点击按钮是可以先立刻消除上一个toast
        toast=Toast.makeText(getApplicationContext(), "", 0);;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void Button1(View v){
        toast.cancel(); 
        toast=Toast.makeText(getApplicationContext(), "系统默认的样式", 1);

        toast.show();
    }  

    public void Button2(View v){
        //清除上一个toast,不会有显示延迟,更加美观。不知道这种方法是否好,如果好请留言,学习学习。
        toast.cancel(); 
        toast=Toast.makeText(getApplicationContext(), "设置Toast显示的位置", 1);
        toast.setGravity(Gravity.CENTER, 0, 0);

        toast.show();
        }
    public void Button3(View v){
        toast.cancel(); 
        toast=Toast.makeText(getApplicationContext(), "设置Toast显示图片和位置", 1);
        toast.setGravity(Gravity.CENTER, 0, 0);
        LinearLayout LinearToast = (LinearLayout) toast.getView();
        LinearToast.setOrientation(LinearLayout.HORIZONTAL);
        ImageView image = new ImageView(getApplicationContext());
        //为了美观,将图片缩小为原来的一半
        InputStream is =this.getResources().openRawResource(R.drawable.ic_launcher); 
        BitmapFactory.Options options=new BitmapFactory.Options(); 
        options.inJustDecodeBounds = false; 
        options.inSampleSize = 2;   //width,hight设为原来的二分一 
        Bitmap btp =BitmapFactory.decodeStream(is,null,options);
        image.setImageBitmap(btp);
        LinearToast.addView(image,0);
        toast.show();
    }

}
Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

3、事件处理

下面以 Button 为例简单介绍一下事件处 理。

  要处理事件,首先要将与该事件有关的控件引入进来,比如要判断用户名是否为空,那么 除了 Button 需要引入外(因为 Button 是触发事件的主体),还需要引入用户名的输入框。 引入之后,button.setOnClickListener()中做处理,这里的 button 是一个变量名,记得 换成自己定义的变量名。

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

onClick 方法带的 view 参数是触发这个单击事件的控件的引用,在这个例子中,view 就是 触发事件的 Button,在 onClick()方法中做事件的处理,例如判断用户名是否为空:Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

关于EditText,Button,RadioGroup各自有的一些方法建议查看API 文档,不在这里一一说明了。

 

4、简单对话框的使用

Android 中最基本的对话框是 AlertDialog,之所以说它最简单,是因为布局和使用的方法 都很简单,布局是写好的。标题,通过 setTitle()方法设置;图标,通过setIcon()方法设置; 显示在中间的主要信息,通过 setMessage() 方法显示等。

AlertDialog.Builder创建对话框的几个常用方法:

setTitle() :设置标题
setIcon() :设置图标
setMessage():设置提示内容
setView() : 设置自定义视图
setItems() :设置对话框要显示的一个list
setMultiChoiceItems() :设置对话框显示的复选框
setNeutralButton() :普通按钮

setPositiveButton() :添加”Yes”按钮
setNegativeButton() :添加”No”按钮
create() : 创建对话框

show() :显示对话框

    显示 一 个 AlertDialog 的基本步骤如下:

 

  (1)创建 AlertDialog.Builder 对象

  (2)调用上面的方法进行设置

  (3)如果需要设置取消按钮,方法原型如下:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  (4)调用 AlertDialog.Builder 的 create() 方法创建 AlertDialog 对象,再调用 AlertDialog 对象的 show()方法将对话框显示出来。

 

  如果不是很明白可以参考下方的实验代码加以理解啦~

 

拓展知识

 

1、Snackbar

  Google 在 2015 年的 IO 大会上发布了较之前更为详细的 Material Design 规范和全新的 Android Design Support Library,Snackbar 就是其中的一个控件,可以用来代替 Toast 信息,除了用户体验更好以外,功能也更强大。先来看一下语法:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  make方法中的三个参数分别是根布局,要显示的消息和时长,这个方法是必须的,之后的方法都不是必须的。定义完之后调用show()方法就可以显示 Snackbar 了。

  setAction方法使该 Snackbar 右侧按钮可以被点击并处理一些事件,两个参数分别是按钮 显示的文本以及处理点击事件的逻辑,形式与 Button 一样。

  setActionTextColor() 是 设 置 右 侧 按 钮 文 本 的 颜 色 , setDuration() 方 法 可 以 定 义 Snackbar 弹出时间长度,单位为 ms,需要注意的是,当右侧按钮被点击之后,Snackbar 会立刻消失。

放一下静态的 Snackbar,实验材料中的 apk 安装启动后,点击拓展启动 的界面用的都是 Snackbar,可以看一下动态效果。

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

在 api 为 19 的模拟器下,按钮显示不出来,可能是不支持,换了api 22 的模拟器就好了。

 

2、TextInputLayout

TextInputLayout 也是 Android Design Support Library 中的一个控件,用于接受用户输 入,与 EditText 配合使用有更好的用户体验,先放几张图:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  一般登录注册界面都需要EditText这个控件来让用户输入信息,同时我们一般会设置一个标签(使用TextView)和EditText的hint属性来提示用户输入的内容,而设计库中高级组件TextInputLayout则专门为EditText设计的,即通过使用TextInputLayout包裹EditText实现当用户开始输入时hint属性值将显示在EditText上面作为一个提示标签,这个过程还带有动画效果,这样就避免了用户输入时输入提示消失的情况,同时,还可以更好地向用户提示错误输入信息。

TextInputLayout的两个功能:

给EditText添加一个带有动画效果的提示标签(利用EditText的hint属性的值作为提示标签内容);

处理错误输入,将错误输入提示信息显示在EditText附近,便于提示用户更好地完成输入。

即:

(1) 实现浮动标签提示效果

  TextInputLayout和FrameLayout一样都是一个ViewGroup,而TextInputLayout包裹的是EditText,并且会将EditText的Android:hint属性值作为提示标签,所以,使用非常简单,可以看到,TextInputLayout 集合了输入提示,报错等功能,并且自带动画效果。

(2) 显示错误输入信息

  TextInputLayout使得我们在验证输入数据是可以更加方便地显示错误输入提示,这样可以使得输入更加友好。

对于处理错误信息,TextInputLayout提供了两个方法:

setError(String message):设置错误提示信息,这个信息将会显示在EditText附近。

setErrorEnabled(boolean enabled):设置错误信息不可以用,也就是移除setError(String message)添加的错误提示信息。

当我们开始在EditText中输入信息的时候,EditText的hint属性值将会显示在EditText上面,并且带有一个动画效果,显示为一个浮动标签。而且,当输入的数据格式不对时,还会显示错误提示在EditText下面。

 

下面来看一下怎么实现:

首先是 xml 布局:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

一个 TextInputLayout 中只能包含一个 EditText,如果想要在预览中看到 TextInputLayout 布局的话,需要在修改对应的 build.gradle 文件中的配置:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

 Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

在 dependencies 中加上 compile ‘com.android.support:design:24.0.0’,然后再同步项 目,就可以显示了:

 Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

在修改了 build.gradle 文件之后,也可以点击 Sync Now同步项目。

 

然后在 java 文件中引入 TextInputLayout,通过 TextInputLayout 获取 EditText 中的内 容:

 Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

TextInputLayout 有特色的一点是可以显示提示信息:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

首先允许使用提示信息 ,然后显示提示信息,如果想使提示信息消失,设置setErrorEnabled(false)即可。

 

其它方法的话自行查阅 API 文档。

 

如果不是很明白可以参考下方的实验代码加以理解啦~

 

实验内容

 

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

实现一个 Android 应用,界面呈现如下效果(界面设计上的要求与实验一相同): 要求:

(1)该界面为应用启动后看到的第一个界面

(2)点击登录按钮:

 

如果用户名为空,弹出 Toast 信息“用户名不能为空”; 如果密码为空,弹出 Toast 信息“密码不能为空”; 如果用户名输入为“Android”,密码为“123456”,弹出如下对话框:

点击“确定”,弹出 Toast 信息——对话框“确定”按钮被点击。,点击“取消”,弹出 Toast 信息——对话框“取消”按钮被点击。

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

否则,弹出如下对话框:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

确定和取消按钮点击后效果参见上一个对话框 点击注册按钮:

如果 RadioButton 选中的是“学生”,那么弹出 Toast 信息“学生身份注册功能尚未开 启”,如果选中的是“教师”,那么弹出 Toast 信息“教师身份注册功能尚未开启”,以 此类推。

 

RadioButton 选择项切换:选择项切换之后,弹出 Toast 信息“XX 身份被选中”,例如从 学生切换到教师,弹出 Toast 信息“教师身份被选中”。

 

实验步骤

 

1、基础内容的实现

在 java 文 件 中 将 布 局 加 载 之 后 , 在 setContentView() 之 后 , 使 用 findViewById()方法可以获得该控件,并声明设置其他类型的元素和类型:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  此次实验用到的事件处理方法一共两个,一个是 Button 的 单 击 事 件 button.setOnClickListener() , 一 个 是 RadioGroup 的 切 换 事 件 radioGroup.setOnCheckedChangeListener()。我们设置 Button 的 单 击 事 件, button.setOnClickListener() 和 RadioGroup 的 切 换 事 件 , radioGroup.setOnCheckedChangeListener()。 处理事件时将与该事件有关的控件引入进来,比如要判断用户名是否为空,那么 除了 Button 需要引入外(因为 Button 是触发事件的主体),还需要引入用户名 的输入框。 引入之后在 SetOnClickListener()中做处理。

 

  在需要弹出 Toast 信息的地方,写上 Toast 的相关代码。这个方法带三个 参数 context,text,duration。context 是一个上下文类型,写上使用 这个 方法的 java 类名加上.this 即可,text 是 Toast 要显示的信息,duration 是 Toast 显示的时间长度,有 Toast.LENGTH_SHORT 和 Toast.LENGTH_LONG 可 选,最后调用 show() 方法将 Toast 显示出来。

 Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  Android 中最基本的对话框是 AlertDialog,它的布局和使用的方法都很简 单,布局是写好的,标题通过 setTitle()方法设置,图标通过 setIcon()方法 设置,显示在中间的主要信息通过 setMessage()方法显示。


  创建 AlertDialog.Builder 对象调用上面的方法进行设置调用 AlertDialog.Builder的create() 方法创建 AlertDialog 对象 , 再调用 AlertDialog 对象的 show()方法将对话框显示出来:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

2、拓展内容的实现:

  在基础实验上的结构和初始声明的基础上,在听取大神们的完成经验后,先完成 TextInputLayout 部分的内容。首先,按照要求,在 xml 布局文件中对 EditText 部 分 进 行 修 改 , 使 用 TextInputLayout 。 TextInputLayout 和 FrameLayout 一样都是一个 ViewGroup,而 TextInputLayout 包裹的是 EditText, 并且会将 EditText 的 Android:hint 属性值作为提示标签用 TextInputLayout 包裹 EditText 并给 EditText 设置了 hint 属性后,这个 EditText 就带有了浮动 提示标签的效果:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

然后在修改对应的 build.gradle 文件中的配置。


  在 java 文件中引入 TextInputLayout,通过 TextInputLayout 获取 EditText 中的内容。在这之前需要对我们需要的两个元素进行声明:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)


  然后获取 EditText 中的内容:

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)


  在登录按钮的监听事件中按照要求实现所需功能:

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  此外需要注意的是:TextInputLayout 使得我们在验证输入数据是可以更加 方便地显示错误输入提示,这样可以使得输入更加友好。

  对于处理错误信息,TextInputLayout 提供了两个方法: setError(String message):设置错误提示信息,这个信息将会显示在EditText 附近。

  setErrorEnabled(boolean enabled):设置错误信息不可以用,也就是移除 setError(String message)添加的错误提示信息。

  显示提示信息 , 符合要求需使提示信息消失,可以在相应位置设置 setErrorEnabled(false)。

  对于Snackbar,make 方法中的三个参数分别是根布局,要显示的消息和时 长,这个方法是必须的,定义完之后调用 show()方法就可以显示 Snackbar。


  而 setAction 方法使该 Snackbar 右侧按钮可以被点击并处理一些事件,两 个参数分别是按钮显示的文本以及处理点击事件的逻辑,形式与 Button 一样。

  Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

  完成实验~

 

实验完整代码

  如下(两个部分的XML布局代码相同,都和上次实验的布局代码相同):

(1)基础部分

content_main.xml

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    android:orientation="vertical">

    <TextView
        android:id="@+id/SYSUTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="@string/sysu"
        android:textSize="20sp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/sysuImage"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/sysu" />


    <android.support.design.widget.TextInputLayout
        android:id="@+id/more_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp">

        <EditText
            android:id="@+id/editTextUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:hint="@string/username2"
            android:inputType="textPersonName" />

    </android.support.design.widget.TextInputLayout>


    <android.support.design.widget.TextInputLayout
        android:id="@+id/more_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp">

        <EditText
            android:id="@+id/editTextPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:hint="@string/password2"
            android:inputType="textPassword" />

    </android.support.design.widget.TextInputLayout>


    <RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioStu"
            style="@style/radioButtonStyle"
            android:checked="true"
            android:text="@string/student" />

        <RadioButton
            android:id="@+id/radioTeacher"
            style="@style/radioButtonStyle"
            android:text="@string/teacher" />

        <RadioButton
            android:id="@+id/radioCorporation"
            style="@style/radioButtonStyle"
            android:text="@string/corporation" />

        <RadioButton
            android:id="@+id/radioManager"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/manager"
            android:textSize="@dimen/etWordSp" />

    </RadioGroup>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/login"
            style="@style/Button"
            android:layout_marginRight="5dp"
            android:text="@string/signIn" />

        <Button
            android:id="@+id/register"
            style="@style/Button"
            android:text="@string/register" />

    </LinearLayout>

</LinearLayout>
Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

MainActivity.java

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)
package com.example.yanglh6.myapplication1;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private RadioGroup radio = null;
    private RadioButton radioStu = null;
    private RadioButton radioTeacher = null;
    private RadioButton radioCorporation = null;
    private RadioButton radioManager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        Button buttonLogin = (Button) findViewById(R.id.login);
        Button buttonRegister = (Button) findViewById(R.id.register);
        final EditText editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        final EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        radio = (RadioGroup) findViewById(R.id.radio);
        radioStu = (RadioButton) findViewById(R.id.radioStu);
        radioTeacher = (RadioButton) findViewById(R.id.radioTeacher);
        radioCorporation = (RadioButton) findViewById(R.id.radioCorporation);
        radioManager = (RadioButton) findViewById(R.id.radioManager);

        buttonLogin.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(editTextUsername.getText().toString())) {
                    Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(editTextPassword.getText().toString())) {
                    Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (editTextUsername.getText().toString().equals("Android") && editTextPassword.getText().toString().equals("123456")) {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("提示")
                            .setMessage("登录成功")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(MainActivity.this, "对话框\"确定\"按钮被点击", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(MainActivity.this, "对话框\"取消\"按钮被点击", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .create()
                            .show();

                } else {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("提示")
                            .setMessage("登录失败")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(MainActivity.this, "对话框\"确定\"按钮被点击", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(MainActivity.this, "对话框\"取消\"按钮被点击", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .create()
                            .show();
                }
            }

        });

        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radioStu.getId()) {
                    Toast.makeText(MainActivity.this, "学生身份被选中", Toast.LENGTH_SHORT).show();
                }
                if (checkedId == radioTeacher.getId()) {
                    Toast.makeText(MainActivity.this, "教师身份被选中", Toast.LENGTH_SHORT).show();
                }
                if (checkedId == radioCorporation.getId()) {
                    Toast.makeText(MainActivity.this, "社团身份被选中", Toast.LENGTH_SHORT).show();
                }
                if (checkedId == radioManager.getId()) {
                    Toast.makeText(MainActivity.this, "管理者身份被选中", Toast.LENGTH_SHORT).show();
                }
            }
        });

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio);
                int checkedId = radioGroup.getCheckedRadioButtonId();
                if (checkedId == R.id.radioStu) {
                    Toast.makeText(MainActivity.this, "学生身份注册功能尚未开启", Toast.LENGTH_SHORT).show();
                } else if (checkedId == radioTeacher.getId()) {
                    Toast.makeText(MainActivity.this, "教师身份注册功能尚未开启", Toast.LENGTH_SHORT).show();
                } else if (checkedId == radioTeacher.getId()) {
                    Toast.makeText(MainActivity.this, "社团身份注册功能尚未开启", Toast.LENGTH_SHORT).show();
                } else if (checkedId == radioCorporation.getId()) {
                    Toast.makeText(MainActivity.this, "管理者身份注册功能尚未开启", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

(2)拓展部分

MainActivity.java

Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)
package com.example.yanglh6.myapplication1;

import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private RadioGroup radio = null;
    private RadioButton radioStu = null;
    private RadioButton radioTeacher = null;
    private RadioButton radioCorporation = null;
    private RadioButton radioManager = null;
    private TextInputLayout usernameText;
    private TextInputLayout passwordText;

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

        usernameText = (TextInputLayout) findViewById(R.id.more_username);
        passwordText = (TextInputLayout) findViewById(R.id.more_password);
        Button buttonLogin = (Button) findViewById(R.id.login);
        final Button buttonRegister = (Button) findViewById(R.id.register);
        final EditText editTextUsername = (EditText) findViewById(R.id.editTextUsername);
        final EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
        radio = (RadioGroup) findViewById(R.id.radio);
        radioStu = (RadioButton) findViewById(R.id.radioStu);
        radioTeacher = (RadioButton) findViewById(R.id.radioTeacher);
        radioCorporation = (RadioButton) findViewById(R.id.radioCorporation);
        radioManager = (RadioButton) findViewById(R.id.radioManager);

        buttonLogin.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usernameEdit = usernameText.getEditText().getText().toString().trim();
                String passwordEdit = passwordText.getEditText().getText().toString().trim();
                if (TextUtils.isEmpty(editTextUsername.getText().toString())) {
                    usernameText.setErrorEnabled(true);
                    usernameText.setError("用户名不能为空");
                    return;
                } else {
                    usernameText.setErrorEnabled(false);
                }
                if (TextUtils.isEmpty(editTextPassword.getText().toString())) {
                    passwordText.setErrorEnabled(true);
                    passwordText.setError("密码不能为空");
                    return;
                } else {
                    passwordText.setErrorEnabled(false);
                }
                if (editTextUsername.getText().toString().equals("Android") && editTextPassword.getText().toString().equals("123456")) {
                    Snackbar.make(getWindow().getDecorView(), "登录成功", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();
                } else {
                    Snackbar.make(getWindow().getDecorView(), "登录失败", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();

                }
            }
        });

        radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radioStu.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "学生身份被选中", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                }
                if (checkedId == radioTeacher.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "教师身份被选中", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                }
                if (checkedId == radioCorporation.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "社团身份被选中", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                }
                if (checkedId == radioManager.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "管理者身份被选中", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                }
            }
        });

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio);
                int checkedId = radioGroup.getCheckedRadioButtonId();
                if (checkedId == R.id.radioStu) {
                    Snackbar.make(getWindow().getDecorView(), "学生身份注册功能尚未开启", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                } else if (checkedId == radioTeacher.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "教师身份注册功能尚未开启", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                } else if (checkedId == radioCorporation.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "社团身份注册功能尚未开启", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                } else if (checkedId == radioManager.getId()) {
                    Snackbar.make(getWindow().getDecorView(), "管理者身份注册功能尚未开启", Snackbar.LENGTH_SHORT)
                            .setAction("按钮", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(MainActivity.this, "Snackbar的按钮被点击了", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setDuration(5000)
                            .show();
                }
            }
        });
    }
}
Android开发2(Toast,AlertDialog,Snackbar,TextInputLayout的使用)

 

对话框总结

  1、Toast:在需要弹出 Toast 信息的地方,写上 Toast 的相关代码。这个 方法带三个参数 context,text,duration。context 是一个上下文类型,写上 使用 这个方法的 java 类名加上.this 即可,text 是 Toast 要显示的信息, duration 是 Toast 显 示 的 时 间 长 度 , 有 Toast.LENGTH_SHORT 和 Toast.LENGTH_LONG 可选,最后调用 show() 方法将 Toast 显示出来。

  2、AlertDialog 的构造方法全部是 Protected 的,所以不能直接通过 new 一个 AlertDialog 来创建出一个 AlertDialog。

要创建一个 AlertDialog,就要用到 AlertDialog.Builder 中的 create()方法。

使用 AlertDialog.Builder 创建对话框需要了解以下几个方法:

setTitle:为对话框设置标题

setIcon:为对话框设置图标

setMessage:为对话框设置内容

setView: 给对话框设置自定义样式

setItems:设置对话框要显示的一个 list,一般用于显示几个命令时

setMultiChoiceItems :用来设置对话框显示一系列的复选框

setNeutralButton:普通按钮

setPositiveButton:给对话框添加”Yes”按钮

setNegativeButton:对话框添加”No”按钮

create:创建对话框

show:显示对话框

 

  3、Snackbar 是 Android design support library 中的另一个组件。使 用 Snackbar,可以在屏幕底部快速的显示一条消息,大体与 Toast 相同,但多了几分灵活性:

一小段时间之后、或者用户与屏幕触发交互,Snackbar 会自动消失; 可以包含一个可选的操作;

把 Snackbar 划出屏幕,可以弃用;

作为一条上下文敏感的消息,也是 UI 的一部分,并在屏幕内所有元素的上 层显示,而不是像 Toast 消息一样位于屏幕*;

一个时刻只能有唯一一个 Snackbar 显示。 make()方法的第一个参数是一个 view,snackbar 会找到一个父 view,以

寄存所赋的 snackbar 值。Snackbar 会沿着 view 的树状路径,找到第一个合适 的布局或窗口视图,作为父 view。

持续时间属性与 Toast 的相同,可选 LENG_SHORT 或者 LENGTH_LONG。

设 置 Action 行 为 事 件 , 使 用 的 方 法 是 public Snackbar setAction (CharSequence text, View.OnClickListener listener); Action 的字体颜色 默认使用系统主题中的如<item name=”colorAccent”>#ff0000</item>

可以通过代码去改变 Action 的字体颜色:Snackbar setActionTextColor (int color)。

 

  4、TextInputLayout

  一般登录注册界面都需要 EditText 这个控件来让用户输入信息,同时我们 一般会设置一个标签(使用 TextView)和 EditText 的 hint 属性来提示用户输 入的内容,而设计库中高级组件 TextInputLayout 则专门为 EditText 设计的, 即通过使用 TextInputLayout 包裹 EditText 实现当用户开始输入时 hint 属性值 将显示在 EditText 上面作为一个提示标签,这个过程还带有动画效果,这样就 避免了用户输入时输入提示消失的情况,同时,还可以更好地向用户提示错误输 入信息。TextInputLayout 的两个功能:

    给 EditText 添加一个带有动画效果的提示标签(利用 EditText 的 hint 属 性的值作为提示标签内容);

    处理错误输入,将错误输入提示信息显示在 EditText 附近,便于提示用户 更好地完成输入。

 

源码下载

源码下载点击这里~

1、本实验实验环境:

操作系统 Windows 10 

实验软件 Android Studio 2.2.1

虚拟设备:Nexus_5X

API:23

2、贴代码的时候由于插入代码框的大小问题,代码格式不太严整,望见谅~


转自杨璐昊的博客:
http://www.cnblogs.com/yanglh6-jyx/p/Android_Activity_Toast_AlertDialog_Snackbar_TextInputLayout.html