Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/218.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 更改样式(使用变量)_Android - Fatal编程技术网

Android 更改样式(使用变量)

Android 更改样式(使用变量),android,Android,我有这个代码,我需要将MyCustonTheme1更改为2或3或4(从SharedReferences的值中,用户选择一个值(1,2,3,4) 在主要活动中,我: if (fade == 500){ animazione = "R.style.MyCustomTheme1"; } if (fade == 1000){ animazione = "R.style.MyCustomTheme2"; }

我有这个代码,我需要将MyCustonTheme1更改为2或3或4(从SharedReferences的值中,用户选择一个值(1,2,3,4)

在主要活动中,我:

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,String)未定义

是否可以将R.style.MyCustomTheme1更改为“animazione”之类的变量


谢谢!

是的,这是可能的。但是你做错了,你应该使用

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

AlertDialog.Builder builder = new AlertDialog.Builder(this, animazione);
请注意,采用主题标识符的重载是在API级别11中添加的,因此它只适用于Android 3.0及更高版本

注意:不鼓励使用此功能。它效率更高 按标识符而不是按名称检索资源

如果您需要按名称查找Android资源(例如,字符串->整数转换),请使用

第一个参数是作为字符串的资源名称。第二个参数是作为字符串的资源类型(例如,
“id”
以查找
R.id
,或
“drawable”
以查找
R.drawable
)。第三个参数是包名

因此,从理论上讲,您应该能够像这样查找样式资源:

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

如果要更改
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+上可用。

+1,完全忘记了它只在API级别11+上可用。谢谢。这也运行android<3?@PolHallen是的,从API级别1(所有版本)开始,这个字符串到int的转换是可用的。当然,您仍然需要Android 3.0+将自定义样式应用于对话框。@quietmint:这对我不起作用,它总是返回0,我有一个定义为“MyApp.Gradient”的样式,该样式对应于context.getResources().getIdentifier(“MyApp\u Gradient”,“style”,context.getPackageName())让我明确一点,在Android 3.0之前,没有办法构建主题化的
AlertDialog
,除非你自己从头开始编写。。。
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);