Android - 如何在运行时注入值/字符串.xml



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

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

但是,您可以使用 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'

在应用程序类中初始化它:

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

最新更新