viewAndroid实践程序员

Android 自定义Toast

2016-10-29  本文已影响1312人  CoderMiner

Android自定义Toast

题图 www.gratisography.com
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
toast.show();
top_right.png

如果不是自定义Toast,请使用makeText(Context, int, int)方法来创建Toast,不要使用Toast的构造方法

自定义布局文件res/layout/custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/ic_action_discover"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              android:text="This is a custom toast"/>
</LinearLayout>

Java 代码逻辑

LayoutInflater inflater = getLayoutInflater();
              View view = inflater.inflate(R.layout.custom_toast, null);
              Toast toast = new Toast(getApplicationContext());
              toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
              toast.setDuration(Toast.LENGTH_SHORT);
              toast.setView(view);
              toast.show();
center.png
private Toast mToast;
private void showToast(String msg){
  if(mToast != null)
      mToast.cancel();
  mToast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
  mToast.show();
}

根据自己的需求开发不同类型的Toast

上一篇下一篇

猜你喜欢

热点阅读