Android中时常要用到toast弹出消息提示,但有的时候,系统的提示样式不能满足设计者与开发者的要求,这时候就需要我们自己来自定义一个toast布局。
先上一段代码。
private void showToast(String tishi) {
// TODO Auto-generated method stub
View layout = inflater.inflate(this,R.layout.toast, null);
TextView title = (TextView) layout.findViewById(R.id.toast_title);
title.setText(tishi);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(layout);
toast.show();
}
这段代码就是弹出toast消息。其中,inflater是private RelativeLayout inflater;this是Activity的上下文。R.layout.toast是自定义的toast布局。
R.layout.toast布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast_bg"
android:padding="30dp" >
<ImageView
android:id="@+id/toast_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher"
android:visibility="gone" />
<TextView
android:id="@+id/toast_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/toast_icon"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:textColor="@color/controle_parental_text_color"
android:textIsSelectable="false"
android:textSize="28sp" />
</RelativeLayout>
在需要弹出提示的地方直接调用showToast方法,传入参数即可。