Android - 如何在运行时注入values/strings.xml

4

假设我有一个Rest API可以获取strings.xml文件。一旦下载完成,是否可以将其设置为应用程序的默认values/strings.xml文件?


为什么你要这样做?在应用程序启动和资源加载之间,会向用户展示哪些资源? - ror
请查看这个答案,看起来你不能从答案中实现它。 - Tamir Abutbul
1个回答

4

字符串资源是静态定义的,无法在运行时更改。

但是,您可以使用Restring库通过添加依赖项在运行时设置和加载字符串:

// Replace bundled strings dynamically
implementation 'dev.b3nedikt.restring:restring:4.0.3'

// Intercept view inflation
implementation 'io.github.inflationx:viewpump:2.0.3'

// Allows to update the text of views at runtime without recreating the activity
implementation 'dev.b3nedikt.reword:reword:1.1.0'

在您的Application类中初始化它:
Restring.init(this,
        new RestringConfig.Builder()
                .stringsLoader(new SampleStringsLoader())
                .loadAsync(false) // If string loader should load strings asynchronously, default true
                .build()
        );

ViewPump.init(ViewPump.builder()
        .addInterceptor(RewordInterceptor.INSTANCE)
        .build());

然后应将其注入上下文:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(ViewPumpContextWrapper.wrap(Restring.wrapContext(newBase)));
}

@Override
public Resources getResources() {
    return Restring.wrapContext(getBaseContext()).getResources();
}

您可以随时加载更多的字符串:

// e.g. locale=Locale.EN newStrings=map of (key-value)s
Restring.setStrings(locale, newStrings);

无需重新启动应用程序即可应用更新后的资源:

// The layout containing the views you want to localise
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Reword.reword(rootView);

更多细节请参考: https://github.com/B3nedikt/restring

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接