Android Toast 自定義背景、圖片 隨心使用

丶ban發表於2016-08-25

Toast原始碼

Toast.makeText()

    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;
    }
com.android.internal.R.layout.transient_notification

<?xml version="2.0" encoding="utf-8"?>
<!--
/* //device/apps/common/res/layout/transient_notification.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?android:attr/toastFrameBackground">

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.Toast"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#BB000000"
        android:shadowRadius="2.75"
        />

</LinearLayout>


那麼我們想要修改Toast的文字訊息樣式,其實就是修改Toast根佈局和message這個TextView。

Toast的另外一種顯示模式就是自定義佈局顯示。這個方法不呼叫Toast.makeText()方法,而是new一個Toast物件,然後呼叫setView()方法。當然自定義佈局就不會載入transient_notification佈局了。


ToastUtil

package test.ban.com.myapplication;/**
 * Created by apple on 16/8/24.
 */

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 作者:ban on 16/8/24 17:55
 */
public class ToastUtil {

    private Toast toast;
    private LinearLayout toastView;

    /**
     * 修改原佈局的Toast
     */
    public ToastUtil() {

    }

    /**
     * 完全自定義佈局Toast
     *
     * @param context
     * @param view
     */
    public ToastUtil(Context context, View view, int duration) {
        toast = new Toast(context);
        toast.setView(view);
        toast.setDuration(duration);
    }

    /**
     * 向Toast中新增自定義view
     *
     * @param view
     * @param postion
     * @return
     */
    public ToastUtil addView(View view, int postion) {
        toastView = (LinearLayout) toast.getView();
        toastView.addView(view, postion);

        return this;
    }

    /**
     * 設定Toast字型及背景顏色
     *
     * @param messageColor
     * @param backgroundColor
     * @return
     */
    public ToastUtil setToastColor(int messageColor, int backgroundColor) {
        View view = toast.getView();
        //設定Toast背景顏色為透明
        view.setBackgroundColor(Color.TRANSPARENT);
        if (view != null) {
            TextView message = ((TextView) view.findViewById(android.R.id.message));
            message.setBackgroundColor(backgroundColor);
            message.setTextColor(messageColor);
        }
        return this;
    }

    /**
     * 設定Toast字型及背景
     *
     * @param messageColor
     * @param background
     * @return
     */
    public ToastUtil setToastBackground(int messageColor, int background) {
        View view = toast.getView();
        //設定Toast背景顏色為透明
        view.setBackgroundColor(Color.TRANSPARENT);
        if (view != null) {
            TextView message = ((TextView) view.findViewById(android.R.id.message));
            message.setBackgroundResource(background);
            message.setTextColor(messageColor);
        }
        return this;
    }

    /**
     * 短時間顯示Toast
     */
    public ToastUtil Short(Context context, CharSequence message) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        return this;
    }

    /**
     * 短時間顯示Toast
     */
    public ToastUtil Short(Context context, int message) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        return this;
    }

    /**
     * 長時間顯示Toast
     */
    public ToastUtil Long(Context context, CharSequence message) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(Toast.LENGTH_LONG);
        }
        return this;
    }

    /**
     * 長時間顯示Toast
     *
     * @param context
     * @param message
     */
    public ToastUtil Long(Context context, int message) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(Toast.LENGTH_LONG);
        }
        return this;
    }

    /**
     * 自定義顯示Toast時間
     *
     * @param context
     * @param message
     * @param duration
     */
    public ToastUtil Indefinite(Context context, CharSequence message, int duration) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, duration);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(duration);
        }
        return this;
    }

    /**
     * 自定義顯示Toast時間
     *
     * @param context
     * @param message
     * @param duration
     */
    public ToastUtil Indefinite(Context context, int message, int duration) {
        if (toast == null || (toastView != null && toastView.getChildCount() > 1)) {
            toast = Toast.makeText(context, message, duration);
            toastView = null;
        } else {
            toast.setText(message);
            toast.setDuration(duration);
        }
        return this;
    }

    /**
     * 顯示Toast
     *
     * @return
     */
    public ToastUtil show() {
        toast.show();

        return this;
    }

    /**
     * 獲取Toast
     *
     * @return
     */
    public Toast getToast() {
        return toast;
    }

}
MainActivity
package test.ban.com.myapplication;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import static android.graphics.Color.WHITE;

public class MainActivity extends Activity {

    private ToastUtil toastUtil;
    private Button mDefault;
    private Button mButton1;
    private Button mButton2;
    private Button mButton3;
    private Button mButton4;
    private ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initButtons();
    }

    /**
     * 初始化控制元件
     */
    private void initButtons() {
        mDefault = (Button) findViewById(R.id.defaultToast);
        mButton1 = (Button) findViewById(R.id.bt1);
        mButton2 = (Button) findViewById(R.id.bt2);
        mButton3 = (Button) findViewById(R.id.bt3);
        mButton4 = (Button) findViewById(R.id.bt4);
        mImageView = (ImageView) findViewById(R.id.iv);
    }


    /**
     * 修改Toast背景色的使用法方法如下:
     *
     * @param v
     */
    public void defaultToast(View v) {
        Toast.makeText(this, "defaultToast", Toast.LENGTH_SHORT).show();
    }

    /**
     * 修改Toast背景色的使用法方法如下:
     *
     * @param v
     */
    public void changeBackGroundColor(View v) {

        toastUtil = new ToastUtil();
        toastUtil.Short(MainActivity.this, "自定義message字型、背景色")
                .setToastColor(WHITE, getResources().getColor(R.color.colorAccent)).show();
    }

    /**
     * 方形的Toast看上去有些呆板,我自定義了一個名為toast_radius.xml的背景
     * <p>
     * 然後設定背景的程式碼改成:
     */
    public void DIYToast(View v) {
        toastUtil.Short(MainActivity.this, "自定義message字型顏色和背景")
                .setToastBackground(WHITE, R.drawable.toast_radius).show();
    }

    /**
     * 向Toast中新增圖示可以這樣
     *
     * @param v
     */
    public void ToastWithPic(View v) {
        ImageView toastImage = new ImageView(getApplicationContext());
        toastImage.setImageResource(R.mipmap.ic_launcher);

        toastUtil.Short(MainActivity.this, "向Toast新增了一個ImageView")
                .setToastBackground(Color.WHITE, R.drawable.toast_radius)
                .addView(toastImage, 0).show();
    }

    /**
     * Toast顯示自定義的佈局
     *
     * @param v
     */
    public void DIYLayout(View v) {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_image, null);
        new ToastUtil(MainActivity.this, view, Toast.LENGTH_SHORT).show();
    }

}
toast_radius.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!-- 填充的顏色 -->
    <solid android:color="#ffc107" />

    <!-- android:radius 弧形的半徑 -->
    <corners android:radius="20dip" />

</shape>
activity_main.xml
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="test.ban.com.myapplication.MainActivity">

    <Button
        android:id="@+id/defaultToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="defaultToast"
        android:text="default"/>
    <Button
        android:id="@+id/bt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="changeBackGroundColor"
        android:text="@string/bt1"
        />

    <Button
        android:id="@+id/bt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="DIYToast"
        android:text="@string/bt2"
        />

    <Button
        android:id="@+id/bt3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ToastWithPic"
        android:text="@string/bt3"
        />

    <Button
        android:id="@+id/bt4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="DIYLayout"
        android:text="@string/bt4"
        />

</LinearLayout>

activity_image.xml

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="test.ban.com.myapplication.MainActivity">

    <ImageView
        android:id="@+id/iv"
        android:background="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>




相關文章