[英]Platform version independent custom dialog with standard icon, title and buttons
我想要存檔的內容:我想要一個帶有自定義視圖的對話框,但我想要AlertDialog
的標准圖標,標題,按鈕。
我正在做的是這個自定義對話框類:
public class CustomDialog extends AlertDialog.Builder {
private Activity activity;
private View root;
public CustomDialog(Activity context) {
super(context);
this.activity = context;
}
public void setView(int layoutResID) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
root = inflater.inflate(layoutResID, (ViewGroup) activity.findViewById(R.id.dialog_root), false);
ScrollView scroller = new ScrollView(activity);
scroller.addView(root);
setView(scroller);
}
public void setCustomView(View v) {
ScrollView scroller = new ScrollView(activity);
scroller.addView(v);
setView(scroller);
}
public View getRoot() {
return root;
}
@Override
public AlertDialog create() {
AlertDialog dialog = super.create();
dialog.getWindow().getAttributes().width = LayoutParams.MATCH_PARENT;
return dialog;
}
}
這非常好,期望在Honeycomb和Honeycomb設備上TextView
顏色不正確。 我正在使用Holo.Light
主題,因此標准文本顏色為黑色,但也是預蜂窩設備上對話框的背景顏色。 在Honeycomb設備上,對話框背景為白色。 所以我做的是,我在values
文件夾的styles.xml
中添加了dialogTextColor=white
,在values-v11
文件夾中添加了dialogTextColor=black
。 然后我必須將style屬性添加到我在自定義對話框中使用的每個TextView
。 這個問題一直持續到ICS,而且很清楚為什么 - > v11。 我可以改變它,但是我希望有一個自定義對話框,它可以完成所有操作:基於應用程序主題,對話框的寬度,預蜂窩,Honeycomb,ICS(以及將來會出現的任何內容)的文本顏色, AlertDialog
的標准按鈕,標題,圖標。
這里的訣竅是Context與主題相關聯。 該主題決定了各種事物,如默認文本顏色等。
在Honeycomb Dialogs之前總是有相同的主題,無論它們是從淺色或深色主題活動生成的,除了列表對話框是深色背景,淺色前景。 在Honeycomb和Forward中,Dialogs具有不同的主題,這些主題由生成它們的Activity確定。
在對話框中膨脹內容時,請始終使用Dialog#getContext()
方法返回的Context,而不是生成Dialog的Activity。 而不是用於獲取上面的LayoutInflater
的代碼行,請嘗試:
LayoutInflater inflater = LayoutInflater.from(getContext());
編輯:看起來你正在使用AlertDialog.Builder而不是Dialog。 AlertDialog.Builder在API 11(Android 3.0,又名Honeycomb)中為此目的添加了一個getContext()
方法,但在此之前它並不存在。 您可以使用ContextThemeWrapper
為舊設備構建自己的主題上下文。 只是確保你永遠不會嘗試在舊版本的平台上調用該方法。 您可以通過簡單的檢查來保護它:
Context themedContext;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
themedContext = getContext();
} else {
themedContext = new ContextThemeWrapper(activity, android.R.style.Theme_Dialog);
}
LayoutInflater inflater = LayoutInflater.from(themedContext);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.