现在的位置: 首页 > 综合 > 正文

Android Toast&Notification(Part I)

2013年05月09日 ⁄ 综合 ⁄ 共 1772字 ⁄ 字号 评论关闭

虽然声明是原创,但是大部分代码和思路还是来自互联网,这里加上自己的总结。

源代码在这里下载

在android中,Toast经常被用来当作应用程序反馈的操作,Toast出现的时候当前的程序界面仍然处于可见

状态并且可以和用户交互。

1、最简单的Toast

创建Toast需要三个参数:当前程序的context、Toast要现实的信息text、显示的时间duration(android中toast显示的时间默认

两种选择LENGTH_LONG和LENGTH_SHORT)

利用函数Toast.makeText(context, text, duration);可以创建一个Toast对象,然后调用toast.show()即可。

	Context context = getApplicationContext();
	CharSequence text = "Ordinary Toast";
	Toast toast = Toast.makeText(context, text, duration);
	//自定义Toast的位置
	//toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
	toast.show();

效果点击Button显示Toast

2、自定义界面的Toast

有时候需要自己定义Toast的界面,这会使得提醒更加的多样化。

首先创建自定义界面对应的xml文件,这里面定义custom_toast.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#DAAA"
    android:orientation="horizontal"
    android:padding="8dp" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dip"
        android:src="@drawable/user" />

    <TextView
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF" />

</LinearLayout>

这段代码来自这里,这个xml文件包含一个ImageView(图片)和TextView(文字),我们这个Toast会以“图片+文字”的形式展现。

使用:

首先创建一个LayoutInflater(具体作用不明),然后获取上述自定义的xml文件

	LayoutInflater inflater = getLayoutInflater();
	View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup)findViewById(R.id.toast_layout_root));

然后自定义TextView中的文字、最后创建Toast对象然后调用.show()方法

	//注意是layout.findViewById()
	TextView text = (TextView)layout.findViewById(R.id.toastText);
	text.setText("This is userDefined Toast");
	Toast toast = new Toast(getApplicationContext());
	toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	toast.setDuration(duration);
	toast.setView(layout);
	toast.show();

效果如图


抱歉!评论已关闭.