2013-08-21 90 views
23

我編寫了一個顯示彈出對話框的android代碼,但我想將背景顏色從黑色更改爲白色,然後更改寫入的顏色。更改彈出對話框的背景顏色

這是該對話框的代碼:

mPrefs = PreferenceManager.getDefaultSharedPreferences(this); 

    Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false); 

    if (!welcomeScreenShown) { 


     String whatsNewText = getResources().getString(R.string.Text); 
     new AlertDialog.Builder(this).setMessage(whatsNewText).setPositiveButton(
       R.string.ok, new DialogInterface.OnClickListener(){ 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }).show(); 
     SharedPreferences.Editor editor = mPrefs.edit(); 
     editor.putBoolean(welcomeScreenShownPref, true); 
     editor.commit(); // Very important to save the preference 
    } 

回答

43

如果你只是想要一個光的主題,不講究特定的顏色,那麼你可以傳遞一個主題ID到AlertDialog.Builder構造。

AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)... 

AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)... 
+0

它完美的作品 – Rick

+0

很好的答案+1 –

+3

它現在已經棄用?現在有什麼建議可以這樣做? – Dinesh

-1

的警告對話框生成器中使用setInverseBackgroundForced(true)反轉背景。

+2

它不起作用:\ – Rick

2

您可以創建自定義alertDialog並使用xml佈局。在佈局中,您可以設置背景顏色和文本顏色。

事情是這樣的:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar); 
LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE); 
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root)); 
dialog.setContentView(view); 
+1

但是我可以只添加一行代碼來改變顏色而不做所有這些東西嗎? – Rick

+7

可能你可以試試這個:getWindow()。setBackgroundDrawableResource(android.R.color.white); – Sushil

+0

它不起作用 – Rick

20

幸得Sushil

創建您AlertDialog像往常一樣:

AlertDialog.Builder dialog = new AlertDialog.Builder(getContext()); 
Dialog dialog = dialog.create(); 
dialog.show(); 

調用展()上的直徑日誌,像這樣設置背景顏色:

dialog.getWindow().setBackgroundDrawableResource(android.R.color.background_dark); 
+3

請小心。雖然這會設置背景顏色,但您將替換之前包含寬度尺寸的可繪製背景。您的結果對話框的大小可能與您未更新背景可繪製的大小不同。 – tir38

43

要擴展@ DaneWhite的答案,您不必依靠內置主題。您可以輕鬆地提供自己的風格:

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert"> 
    <item name="android:background">@color/myColor</item> 
</style> 

,然後在Builder構造應用它:

AlertDialog alertDialog = new AlertDialog.Builder(getContext(), R.style.MyDialogTheme) 
     ... 
     .create(); 

這應該工作您是否使用android.support.v7.app.AlertDialogandroid.app.AlertDialog

這也適用好過@ DummyData的答案,因爲你不調整對話框的大小。如果將窗口的背景設置爲可繪製,則會覆蓋一些現有的尺寸信息並獲得非標準寬度的對話框。

如果您在主題上設置了背景,並在對話框中設置了主題,則最終會出現一個對話框,該對話框的顏色是您想要的但仍然是正確的寬度。

+0

終於!工作解決方案非常感謝你。 – DmitryKanunnikoff

1

對於任何對話框調用myDialog,呼籲myDialog.show();後,您可以撥打:

myDialog.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, CUSTOM_COLOR)); 

其中CUSTOM_COLOR是8位十六進制格式,恩。 0xFF303030。這裏,FF是alpha值,其餘的是十六進制的顏色值。

-1

只更新您的導入。

import android.app.AlertDialog; 

import android.support.v7.app.AlertDialog; 

它將是固定的。