2012-12-29 39 views
2

我已經使用此代碼,並且需要將MyCustonTheme1更改爲2或3或4(由sharedpreferences提供值,用戶選擇值(1,2,3,4)更改樣式(使用變量)

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyCustomTheme1); 

在MainActivity我有:

if (fade == 500){ 
      animazione = "R.style.MyCustomTheme1"; 
     } 
     if (fade == 1000){ 
      animazione = "R.style.MyCustomTheme2"; 
     } 
      [...] 

現在,我需要把 「animazione」 這樣的代碼:

AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione); 

構造AlertDialog.Builder(MainActivity,字符串)未定義

它是否可能改變R.style.MyCustomTheme1變量像「animazione」?

謝謝!

+1

讓我清楚,有**沒有**的方式來建立一個主題'AlertDialog'直到_Android 3.0_,除非你自己從頭開始編碼... –

回答

1

注意:不鼓勵使用此功能。 通過標識符而不是按名稱檢索資源要高效得多。

如果你需要按名稱查找的Android資源(例如字符串 - > INT轉換),用getIdentifier(String, String, String)

第一個參數是資源名稱作爲字符串。第二個參數是資源類型作爲字符串(例如,"id"查看R.id"drawable"查看R.drawable)。第三個參數是包名。

所以,從理論上講,你應該能夠查找一個樣式資源是這樣的:

int style = getResources().getIdentifier("MyCustomTheme1", "style", getPackageName()); 
+0

謝謝。這也運行android <3? –

+0

@PolHallen是的,這個String-to-int轉換可以在API Level 1(所有版本)中使用。當然,您仍然需要Android 3.0+將自定義樣式應用到對話框中。 – user113215

1

是的,它的可能性。但是,你做錯了,你應該使用

int animazione = R.style.MyCustomTheme1; // look, no quotes! 

AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione); 

注意過載採取主題標識API級別11加入,所以它只會在Android 3.0的和更高版本。

+0

+1,完全忘了它只能從API等級11+ – Ahmad

1

如果你想改變AlertDialog.Builder的風格,那麼你就必須在上下文和傳遞樣式。樣式是int,但是你傳入一個字符串。更改爲:

int animazione; // change it to an int 

if (fade == 500){ 
      animazione = R.style.MyCustomTheme1; 
     } 
else if (fade == 1000){ // also add an 'else' in here (else if) 
      animazione = R.style.MyCustomTheme2; 
     } 
      [...] 

AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione); 

就像k-ballo已經指出的那樣,這隻能從API級別11+獲得。