android自定義toast(widget開發(fā))示例
1、Toast控件:
通過查看源代碼,發(fā)現(xiàn)Toast里面實現(xiàn)的原理是通過服務Context.LAYOUT_INFLATER_SERVICE獲取一個LayoutInflater布局管理器,從而獲取一個View對象(TextView),設置內(nèi)容將其顯示
public static Toast makeText(Context context, CharSequence text, 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;
}
定義布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/notification" />
<TextView
android:id="@+id/tv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="text"
/>
</LinearLayout>
自定義MyToast類:
public class MyToast {
/**
* 顯示自定義的土司
* @param context 上下文
* @param iconid 圖標的id
* @param text 顯示的文本
*/
public static void showToast(Context context,int iconid, String text){
View view = View.inflate(context, R.layout.my_toast, null);
TextView tv = (TextView) view.findViewById(R.id.tv_my_toast);
ImageView iv = (ImageView) view.findViewById(R.id.iv_my_toast);
iv.setImageResource(iconid);
tv.setText(text);
Toast toast = new Toast(context);
toast.setDuration(0);
toast.setView(view);
toast.show();
}
}
相關文章
DrawerLayout的簡單使用及側(cè)滑菜單實現(xiàn)詳解
這篇文章主要為大家介紹了DrawerLayout的簡單使用及側(cè)滑菜單實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04Android實現(xiàn)EditText控件禁止輸入內(nèi)容的方法(附測試demo)
這篇文章主要介紹了Android實現(xiàn)EditText控件禁止輸入內(nèi)容的方法,涉及Android針對EditText控件屬性設置的相關技巧,需要的朋友可以參考下2015-12-12ubuntu 12.10 上 android 編譯環(huán)境搭建的深入解析
本篇文章是對ubuntu 12.10上android 編譯環(huán)境的搭建進行了詳細的分析介紹,需要的朋友參考下2013-06-06Android開發(fā)中實現(xiàn)應用的前后臺切換效果
這篇文章主要介紹了Android開發(fā)中實現(xiàn)應用的前后臺切換效果的方法,文章最后還附帶了監(jiān)聽程序是否進入后臺的判斷方法,需要的朋友可以參考下2016-02-02Android RecyclerView網(wǎng)格布局(支持多種分割線)詳解(2)
這篇文章主要為大家詳細介紹了Android RecyclerView網(wǎng)格布局,支持多種分割線,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02Android Cocos Creator游戲開發(fā)平臺打包優(yōu)化實現(xiàn)方案
Cocos Creator是一款輕量、高效、免費開源的跨平臺游戲引擎,同時也是實時3D內(nèi)容創(chuàng)作平臺,不僅支持2D、3D的游戲開發(fā),同時在HMI、IoT、XR、虛擬人偶等領域,均可提供一套完善的行業(yè)解決方案2022-11-11