年前的时候,静不下心来学东西,看着Toast默认样式不爽,就进去大致看一下它的源码然后自己借用了一下它原来的实现,改了个自定义的Toast。(初学者)
最终完成,弹出Toast的代码这样写:
Toast.makeText(this, "再次返回,退出程序", Toast.LENGTH_SHORT).myShow();
哈哈。方法名可以自定义。
下面是自定义Toast类的代码:
public class Toast {
//声明Context对象、要弹出的字符串、显示时长
private static Context context;
private static String str;
private static int duraiton;
//声明时长的两个常量(就是使用原Toast的)
public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;
public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;
private Toast(Context context, String str, int duraiton){
Toast.context = context;
Toast.str = str;
Toast.duraiton = duraiton;
}
public static Toast makeText(Context context, String str, int duraiton){
return new Toast(context, str, duraiton);
}
public void myShow(){
//注意,这里创建的是原Toast,需要加全包名
android.widget.Toast toast = new android.widget.Toast(context);
//定义Toast的样式(在布局文件中)
View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
((TextView)view.findViewById(R.id.my_toast_content)).setText(str);
//设置view
toast.setView(view);
//设置弹出的位置
//toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
}
toast_view.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="111"
android:id="@+id/my_toast_content"
android:textColor="#e4d63f"
android:background="@drawable/toast_shape"
android:paddingTop="@dimen/padding5"
android:paddingBottom="@dimen/padding5"
android:paddingStart="@dimen/padding10"
android:paddingEnd="@dimen/padding10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
需要注意的一个地方是,自定义样式里的textview是需要我们根据传入的str来进行设置的,在执行toast.setView(view)的时候,只是在toast.show()的时候显示我们传入的view视图,而不进行其他操作。
最后,调用处导包要导自己写的Toast的路径。
/……….后记: 挺好玩的,反正我觉着 :P …………/