Android自定義Toast

自定義Toast

一直以來都沒有寫博客的習慣,但是喜歡從別人的博客中吸取一些經驗教訓,但是隨着時間的推移,自己慢慢發現東西越來越多,自己的記憶就越來越的不牢靠,所以我會嘗試着把自己積累的一些東西,解決的一些問題記錄下來,以便不會重蹈覆轍。

Toast應該是每個安卓應用開發者最早接觸的一個知識點之一。原生的toast只提供了設置文本,時長,位置的一些簡單的操作;實際上我們的需求可能會複雜的多,這時候大家往往會通過setView(View view)的方式來改變吐司裏面的內容,之前自己一直也是這麼做的,後來一次沒事的時候打開了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的佈局文件,我們點開一看究竟:

<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>

跟我們設想的差不多,內部是一個Textview,但是發現它的外部容器實際上是一個豎直方向上的LinearLayout,假如我們能夠拿到這個容器,我們不就可以動態的往裏面添加view裏嗎,看到這裏我趕緊看了一下Toast的方法,果然發現toast.getView()這個方法,經試驗完全有效,加入自己的ToastUtil的工具類:

/**
 * 向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 background
 * @return
 */
public ToastUtil setToastBackground(int messageColor, int background) {
    View view = toast.getView();
    if(view!=null){
        TextView message=((TextView) view.findViewById(android.R.id.message));
        view.setBackgroundResource(background);
        message.setTextColor(messageColor);
    }
    return this;
}

這樣我們就少了原生帶來的很多的不靈活性,自己可以完全隨心所欲的定製自己的toast

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章