当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发Toast如何使用

Android开发Toast如何使用

2020年10月12日  | 移动技术网移动技术  | 我要评论
Toast1、总结:Toast是应用运行期间,通过类似于对话框的方式向用户展示消息提示Toast只占用很少屏幕,并且在一段时间会自动消失Content content=getApplicationContent(); //获得应用上下文string text="准备Toast中显示文本"; //准备Toast中显示文本int duration=Toast.LENGTH_LONG

Toast

1、总结:


Toast是应用运行期间,通过类似于对话框的方式向用户展示消息提示

Toast只占用很少屏幕,并且在一段时间会自动消失

Content content=getApplicationContent(); //获得应用上下文 string text="准备Toast中显示文本"; //准备Toast中显示文本 int duration=Toast.LENGTH_LONG //用于设置Toast显示时间 Toast toast=Toast.makeText(context,text duration) //生成Toast对象 toast.show() //显示Toast通知 


代码通过Toast.makeText(context,text,duration)来创建Toast对话框

参数:

content是应用运行环境的上下文,在主活动中也可以直接使用MainActivity.this来获得上下文

text是Toast中显示的文本

duration设置Toast通知显示的时间,Toast.LENGTH_LONG表示显示较长时间,5S左右

Toast.LENGTH_SHORT表示显示较短时间,3S左右

toast.show()方法用于显示Toast通知

但是通常情况下Toast显示在屏幕底部居中位置,调用 setGravity()方法可设置Toask显示位置

toask.setGravity(Gravity.CENTER_VERTICAL,0,0); //设置Toast在屏幕中心


通常常量Gravity.CENTER_VERTICAL表示在屏幕居中位置,类似的还有Gravity.TOPGravity.LEFT

setGravity()方法的第2个参数,第三个参数表示在x轴y轴的偏移量


2、案例:

运行结果:

在这里插入图片描述


activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout
    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" tools:context=".MainActivity"> <Button
       android:layout_marginTop="10dp" android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Toast.LENGTH_LONG"/> <Button
       android:layout_marginTop="20dp" android:id="@+id/btn2" android:layout_below="@+id/btn1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Toast.LENGTH_SHORT"/> </RelativeLayout>


MainActivity.java

package com.example.textlistview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv=findViewById(R.id.text); Button b1=findViewById(R.id.btn1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"这是长时间显示Toast",Toast.LENGTH_LONG).show(); } }); Button b2=findViewById(R.id.btn2); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"这是短时间显示Toast",Toast.LENGTH_SHORT).show(); } }); } }

本文地址:https://blog.csdn.net/qq_45907053/article/details/109039714

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网