我爲我的活動創建了自定義主題,它們都使用它。在主題中,我設置了android:background,並且這會導致任何對話框或吐司消息看起來很奇怪。吐司背景更改爲匹配活動的主題
如何防止烤麪包和其他對話框吸收主題屬性?
我爲我的活動創建了自定義主題,它們都使用它。在主題中,我設置了android:background,並且這會導致任何對話框或吐司消息看起來很奇怪。吐司背景更改爲匹配活動的主題
如何防止烤麪包和其他對話框吸收主題屬性?
您可以輕鬆地通過下面的代碼創建自定義舉杯:
Toast toast = Toast.makeText(context, resTxtId, Toast.LENGTH_LONG);
View view = toast.getView();
view.setBackgroundResource(R.drawable.custom_bkg);
TextView text = (TextView) view.findViewById(android.R.id.message);
/*here you can do anything with text*/
toast.show();
或者你可以實例化一個完全自定義的敬酒:
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_LONG);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, null);
toast.setView(view);
toast.show();
對話框定製是一個更復雜的程序。但是也有類似的解決方法。
這裏是一個完整的例子,用於跨活動的定製Toast。
displayToast
// display customized Toast message
public static int SHORT_TOAST = 0;
public static int LONG_TOAST = 1;
public static void displayToast(Context caller, String toastMsg, int toastType){
try {// try-catch to avoid stupid app crashes
LayoutInflater inflater = LayoutInflater.from(caller);
View mainLayout = inflater.inflate(R.layout.toast_layout, null);
View rootLayout = mainLayout.findViewById(R.id.toast_layout_root);
ImageView image = (ImageView) mainLayout.findViewById(R.id.image);
image.setImageResource(R.drawable.img_icon_notification);
TextView text = (TextView) mainLayout.findViewById(R.id.text);
text.setText(toastMsg);
Toast toast = new Toast(caller);
//toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setGravity(Gravity.BOTTOM, 0, 0);
if (toastType==SHORT_TOAST)//(isShort)
toast.setDuration(Toast.LENGTH_SHORT);
else
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(rootLayout);
toast.show();
}
catch(Exception ex) {// to avoid stupid app crashes
Log.w(TAG, ex.toString());
}
}
和toast_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
我意識到這個問題已經回答後是很老在這個階段。不過,我想我會爲那些遇到這個問題的人留下一個答案。
我遇到了麻煩,這個問題今天我解決方式,它是通過顯示這樣我的吐司消息:
Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
與此相反(假設消息正在從視圖中調用) :
Toast.makeText(v.getContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
它清除了我遇到的問題。反正希望它有幫助。這裏是關於類似主題的鏈接。
Javacadabra答案在我看來是更好 – rubdottocom
難道我讀的問題錯了嗎?但問題是如何防止它被定製,並且你在說明如何定製它? – WORMSS
@WORRMS,你是對的,但是......就主題改變而言,任何不適用這個主題的烤麪包都是一個自定義烤麪包(因爲我們需要「重新設計」它) – Dmitry