安卓写自定义吐司样式,先查看Toast类的源码:
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
以上代码片是安卓的吐司源码,自定义样式,先有一个自己的布局,布局中有一个TextView来展示文字信息。设置一下时间duration。
我的自定义吐司:
/**
* Created by niyl on 2016/5/30.
*/
public class MyToast {
public MyToast(Context context,String prompt) {
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
View view = View.inflate(context, R.layout.toast_custom,null);
TextView tvPrompt = (TextView)view.findViewById(R.id.tv_prompt);
tvPrompt.setText(prompt);
toast.setView(view);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
页面布局补一下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#808080"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="16sp"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical"
android:textColor="#ffffff"
android:id="@+id/tv_msg"
android:padding="15dp"
/>
</LinearLayout>
我将吐司设置在屏幕中间,并直接调show()方法。这样,吐司对象创建便执行了吐司效果。
效果图: