I'm using a LayoutInflater to inflate a custom layout to generate invoices and receipts as Bitmaps then I send them to the printer or export them as png files, Like this:
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.layout_invoice, null);
// Populate the view here...
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(paperWidth, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
view.layout(0, 0, width, height);
Bitmap reVal = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(reVal);
view.draw(canvas);
Now this code works perfectly but it inflates the view in the device's current language. Sometimes i need to generate invoices in other language, Is there any way to inflate that view in custom locale?
Note: I tried to change the locale before inflating the view and reset it afterwards:
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = new Locale("fr");
// Inflate the view
// ...
// Reset the locale to the original value
But it doesn't work for some reason. Any assistance would be appreciated.
You can create localized context with this simple class
public class LocalizedContextWrapper extends ContextWrapper {
public LocalizedContextWrapper(Context base) {
super(base);
}
public static ContextWrapper wrap(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLocale(locale);
context = context.createConfigurationContext(configuration);
} else {
configuration.locale = locale;
context.getResources().updateConfiguration(
configuration,
context.getResources().getDisplayMetrics()
);
}
return new LocalizedContextWrapper(context);
}
}
And use this it like that
Context localizedContext = LocalizedContextWrapper.wrap(context, locale);