天天看點

android應用程式中使用自定義Toast控件

自定義Toast對于原生Toast的美中不足得到了美化。可以将自定義的ImageView和TextView控件添加到其中

先看看截圖吧。

android應用程式中使用自定義Toast控件
android應用程式中使用自定義Toast控件

通過自定義實作之後,這是基本效果。

可以實作Toast整體背景更換,textView背景的修改,

toast左端圖檔的屬性可以在當做imageView來設定其屬性,

toast文字的屬性可以當做對textView的屬性進行設定。

部分代碼如下:

//省略部分引用……

public class MyToast {
public static void myToastShow(Context context,int imageResId,String content,int duration)
{ 
Toast toast=new Toast(context);
toast.setDuration(duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 25);
LinearLayout toastLayout=new LinearLayout(context);
toastLayout.setOrientation(LinearLayout.HORIZONTAL);
toastLayout.setGravity(Gravity.CENTER_VERTICAL);

ImageView imageView=new ImageView(context);
imageView.setImageResource(imageResId);
toastLayout.addView(imageView, 38, 38); //将imageView添加到toastLayout當中,後面的兩個設定為相應view的寬和高。

TextView tv_content=new TextView(context);
tv_content.setText(content);
tv_content.setTextSize(16);
tv_content.setGravity(Gravity.CENTER);
tv_content.setBackgroundResource(R.drawable.toast_bg);
toastLayout.addView(tv_content, LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);   //将textView 添加到toast當中,後面的參數為textView的長寬。
toast.setView(toastLayout);
toast.show();

}
}
           

之後就可以在其他類中或者activity之中調用此方法顯示自定義toast,

需要設定的隻是toast要顯示的圖檔,文字,時間。

截圖中的效果代碼如下。

MyToast.myToastShow(getApplicationContext(), R.drawable.show_user, "As you can see,this is btn1", 
Toast.LENGTH_LONG);
MyToast.myToastShow(getApplicationContext(), R.drawable.ic_menu_day, "As you can see,this is btn2"+
",and this is different form btn1", 
Toast.LENGTH_LONG);
           

源碼下載下傳:點選進入

繼續閱讀