Consider that I have an Rest API that let me fetch a strings.xml
file.
Once downloaded is it posible set as the default values/strings.xml
file of the app?
Asked
Active
Viewed 826 times
4

Ricardo
- 7,921
- 14
- 64
- 111
-
Why would you do that. What kind of resources would be shown to user between app start and resource loaded? – ror Jun 02 '20 at 10:16
-
Check [this answer](https://stackoverflow.com/questions/8258650/is-it-possible-to-change-the-value-of-a-string-added-in-res-strings-xml-on-andro/8258712) , it looks like you can not do it from the answer – Tamir Abutbul Jun 02 '20 at 10:26
1 Answers
4
String resources are static defined and can not be changed at runtime.
However, you could use the Restring library to set and load strings at runtime by adding the dependencies:
// 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'
Initialising it in your Application class:
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());
Then it should be injected into context:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(Restring.wrapContext(newBase)));
}
@Override
public Resources getResources() {
return Restring.wrapContext(getBaseContext()).getResources();
}
And you can load more strings at any time:
// e.g. locale=Locale.EN newStrings=map of (key-value)s
Restring.setStrings(locale, newStrings);
And apply updated resources without restarting the app:
// The layout containing the views you want to localise
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Reword.reword(rootView);
More details: https://github.com/B3nedikt/restring

jeprubio
- 17,312
- 5
- 45
- 56