Reputation: 1872
I've this code and I need to change MyCustonTheme1 to 2 or 3 or 4 (From a value by sharedpreferences, user choose a value (1,2,3,4)
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyCustomTheme1);
In MainActivity I've:
if (fade == 500){
animazione = "R.style.MyCustomTheme1";
}
if (fade == 1000){
animazione = "R.style.MyCustomTheme2";
}
[...]
Now, I need put "animazione" like this code:
AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione);
The constructor AlertDialog.Builder(MainActivity, String) is undefined
Is it possibile change R.style.MyCustomTheme1 to variable like "animazione"?
thanks!
Upvotes: 3
Views: 1363
Reputation: 72673
If you want to change the style of the AlertDialog.Builder
then you'll have to pass in a context and the style. The style is a int, but you are passing in a string. Change it to this:
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);
Like k-ballo already pointed out this is only available from API level 11+.
Upvotes: 1
Reputation: 14164
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
If you need to look up Android resources by name (e.g., String -> int conversion), use getIdentifier(String, String, String)
.
The first parameter is the resource name as a string. The second parameter is the resource type as a string (e.g., "id"
to look in R.id
, or "drawable"
to look in R.drawable
). The third parameter is the package name.
So, theoretically, you should be able to look up a style resource like this:
int style = getResources().getIdentifier("MyCustomTheme1", "style", getPackageName());
Upvotes: 2
Reputation: 81409
Yes, its possible. But you are doing it wrong, you should use
int animazione = R.style.MyCustomTheme1; // look, no quotes!
AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione);
Note that the overload taking a theme identifier was added in API level 11, so it will only work in Android 3.0 and later.
Upvotes: 1