toast的簡單用法

廢話很少說,直接上代碼:java

/**
 * toast自帶的設置圖片類型的方法
 *
 * @param view
 */
public void btn1(View view) {
    Toast toast = Toast.makeText(MainActivity.this, "帶圖片的toast", Toast.LENGTH_SHORT);
    ImageView imageView = new ImageView(this);
    imageView.setImageResource(R.mipmap.ic_launcher);

    toast.setGravity(Gravity.CENTER, 0, 0);//若是不加這個佈局設置,圖片就會顯示在文字上面;
    LinearLayout toastView = (LinearLayout) toast.getView();//先獲取toast的佈局對象
    toastView.addView(imageView);//給佈局對象添加view

    toast.show();
}

效果以下:android

設置toast的位置:app

/**
 * 設置toast顯示位置
 *
 * @param view
 */
public void btn2(View view) {
    Toast toast = Toast.makeText(getApplicationContext(), "lalala", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);//在這裏有各類選項,看單詞就知道什麼意思了
    toast.show();
}
//比較簡單不貼圖了


徹底自定義的toast:佈局

1. 佈局文件  toast_define:
this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:background="@drawable/ab"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#7030ff8f"
        android:drawableLeft="@android:drawable/btn_star_big_on"
        android:gravity="center"
        android:text="自定義toast佈局"
        android:textSize="25sp" />

    <ImageView
        android:id="@+id/iv_content"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#f9f9"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#7031ffff"
        android:gravity="center"
        android:text="徹底自定義的toast"
        android:textSize="25sp" />

</LinearLayout>

2.代碼部分:
code

/**
 * 徹底自定義的toast佈局
 *
 * @param view
 */
public void btn3(View view) {
    Toast toast = new Toast(this);
    View toastView = LayoutInflater.from(this).inflate(R.layout.toast_define, null);
    TextView content = (TextView) toastView.findViewById(R.id.tv_content);

    content.setText("煩煩煩煩");
    content.setTextColor(Color.parseColor("#ff0000"));

    toast.setGravity(Gravity.TOP, 0, 0);
    toast.setView(toastView);
    toast.show();
}

顯示效果:xml

比較醜,講究看看吧;
對象

相關文章
相關標籤/搜索