我正在使用LayoutInflater来扩充自定义布局以生成发票和收据作为位图然后我将它们发送到打印机或将它们导出为png文件,如下所示:
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);
现在这段代码完美无缺,但它会在设备的当前语言中膨胀视图。有时我需要用其他语言生成发票,有没有办法在自定义区域设置中膨胀该视图?
注意:我尝试在给视图充气之前更改区域设置,然后重置它:
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = new Locale("fr");
// Inflate the view
// ...
// Reset the locale to the original value
但由于某种原因它不起作用。任何帮助将不胜感激。
答案 0 :(得分:3)
您可以使用此简单类创建本地化上下文
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);
}
}
使用它就像那样
Context localizedContext = LocalizedContextWrapper.wrap(context, locale);
答案 1 :(得分:0)
我想通了,我需要使用自定义区域设置创建一个新的上下文,并使用我的新上下文来扩展视图:
Configuration config = new Configuration(resources.getConfiguration());
Context customContext = context.createConfigurationContext(config);
Locale newLocale = new Locale("fr");
config.setLocale(newLocale);
LayoutInflater inflater = LayoutInflater.from(customContext);
(很抱歉在我尽我所能之前询问)。