Android 的 Toast 是以一种一闪即过的方式展示信息很好的方式,比如保存操作之后的保存成功提示。默认的Toast是文本信息,可以设置Toast的位置。能否在开发过程中自定义Toast呢?比如文本+图这种形式的Toast,这种方式是可以的,今天写了一个例子,现贴出来作为记录。
1)CustomToastActivity
一个继承自Activity的类,点击Activity里面的Button的时候,弹出用户自定义Toast
package com.augmentum.example;
import com.example.androidexample.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class CustomToastActivity extends Activity {
private Button btnToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toast);
LayoutInflater inflater = getLayoutInflater();
View toastLayout = inflater.inflate(R.layout.toast,
(ViewGroup)findViewById(R.id.toast_layout));
final Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 10);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
btnToast = (Button)findViewById(R.id.btnToast);
btnToast.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
toast.show();
}
});
}
}
2) activity_toast.xml
CustomToastActivity的布局文件,仅包含一个Button
<?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:orientation="horizontal" >
<Button
android:id="@+id/btnToast"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:text="Show Custom Toast"
android:layout_weight="1"/>
</LinearLayout>
3)toast.xml
用户自定义的Toast,包含一个ImageView和一个TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/image"
android:src="@+drawable/kugou"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:contentDescription="I am a image"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a custom toast."
android:textSize="25sp"/>
</LinearLayout>
4)总结
A) 用户自定义的Toast使用了LayoutInflater类,该类是生成View的,通过这个类生成View的实例,然后赋值给Toast实例的view属性。
B)Toast的位置可以通过Gravity属性来设置。
5)运行效果