假设我有一个Rest API可以获取strings.xml
文件。一旦下载完成,是否可以将其设置为应用程序的默认values/strings.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);