如果有一天,突发奇想的PM想让你实现这种提示效果?用户点击按钮—–弹出一个提示信息,类似于上图GIF展示的效果,我们该怎么实现呢? 当然方式有很多种,比如PopupWindow,或者动画,其实,还有一种我们用的最多的—-Toast也可以实现这种方式,而且比其他方式更简单。
Toast,开发中最简单,最常见的提示方式,一般使用,都是简单的
Toast toast = Toast.makeText(this,"提示!!!!", Toast.LENGTH_SHORT); toast.show();灰黑色背景,加上一句提示语句,是不是太过单调呢? 那就试试不一样的Toast
1.设置Gravity
Toast toast = Toast.makeText(this, "提示!!!!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); 对Toast对象重新设置Gravity,除了设置CENTER,还有很多位置可选,可以根据需求自己设定
2.设置设置Margin: toast.setMargin(0.5f,0.2f);
3.设置展示时长 toast.setDuration(Toast.);
不过只要Toast.LENGTH_LONG和LENGTH_SHORT可选。
4.阅读Toast源码,会发现Toast有个方法, public void setView(View view)意味着什么,我们可以给Toast设置一个View,也就是说,可以自定义Toast的样式啊
动手吧
先来个布局:
"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="200dp" android:layout_height="150dp" android:background="@drawable/shape_bg" android:orientation="vertical"> <ImageView android:layout_width="200dp" android:layout_height="100dp" android:padding="5dp" android:src="@drawable/favorite" /> <TextView android:layout_width="200dp" android:layout_height="match_parent" android:gravity="center" android:text="花式Toast" android:textColor="@color/white" /> </LinearLayout>效果
Activity的布局很简单:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/bt_toast" android:layout_width="200dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="50dp" android:background="@color/colorPrimary" android:text="Toast" /> </RelativeLayout>一个水平居中的Button,初始化控件:
toast = new Toast(this); View v = getLayoutInflater().inflate(R.layout.toast, null); toast.setView(v); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG);点击Button时,展示Toast:
btToast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toast.show(); } });轻轻松松,实现了效果。
根据Toast的setView()方法,可以自定义Toast的样式,如果有这种需求,还是很方便的,不过,谷歌大大期望用最简单的方式给用户最直接的提示,所以这个方式谷歌并不推荐,但并不妨碍我们自己去定制自己的Toast,给用户不一样的体验
