Java Android设置资源文件项

Java Android设置资源文件项,java,android,android-resources,Java,Android,Android Resources,在android中,getResource()方法可用于获取xml文件中声明的资源。比如: <resources> <string name="sample_1">Sample 1</string> <string name="sample_2">Sample 2</string> <string name="sample_3">Sample 3</string> <string name="sample_

在android中,getResource()方法可用于获取xml文件中声明的资源。比如:

<resources>
<string name="sample_1">Sample 1</string>
<string name="sample_2">Sample 2</string>
<string name="sample_3">Sample 3</string>
<string name="sample_4">Sample 4</string>
<string name="sample_5">Sample 5</string>
</resources>
所以get方法是用来访问它们的,但是set方法在哪里呢。我在网上搜索了很多,但没有找到任何有用的东西。通过java在运行时设置字符串和颜色资源的方法是什么。互联网上充满了这样的例子:

TextView ab = findviewbyid(........);
ab.setText("bla bla");
我不想这样,我想直接更改资源文件项,如:

setResouces(R.color.primarycolor) to #00000

有没有像上面那样的解决方案

我认为没有setResources方法。您可以通过以下方式动态获取字符串资源

Resources res = getResources();
String text = String.format(res.getString(R.string.sample_1));


TextView ab = findviewbyid(........);
//在string.xml中设置值的步骤

ab.setText("text");

虽然没有这样的方法来设置资源,但您可以使用build.gradle在运行时创建资源

buildTypes {
        def var = "";
        debug {
            var = "debug"
            buildConfigField "String", "BUILD_DATE", "\"12345\""
            resValue "string", "buildTime", "12345678"
            }
}

在build.gradle中添加类似的代码将在构建应用程序时创建字符串资源。

没有set方法,因为无法写入资源。您可以使用其他方法,例如将VAULE保存到SharedReference或数据库中。或者其他文本或xml文件。我认为没有set方法,也没有必要这样做。你为什么需要这个?请描述您的用例,可能还有其他解决方案。对不起。不可能。没有办法更新资源值吗?基本上我的应用程序使用很多颜色,颜色是在线获取的,因为现在我正在实例化每个对象来设置颜色。如果有一种方法可以直接更新资源文件,这将很有帮助,并减少代码。请进一步解释这一点。这是在构建应用程序时使用gradle创建资源的一种方法。它将创建名为“buildTime”的字符串资源,其值为“12345678”。在您构建应用程序之后
buildTypes {
        def var = "";
        debug {
            var = "debug"
            buildConfigField "String", "BUILD_DATE", "\"12345\""
            resValue "string", "buildTime", "12345678"
            }
}