在 Android 中使用自定义语言环境扩充视图

Inflating a view with custom locale in Android

我正在使用 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

但由于某种原因它不起作用。如有任何帮助,我们将不胜感激。

我明白了,我需要使用自定义语言环境创建一个新上下文并使用我的新上下文扩充视图:

Configuration config = new Configuration(resources.getConfiguration());
Context customContext = context.createConfigurationContext(config);

Locale newLocale = new Locale("fr");
config.setLocale(newLocale);

LayoutInflater inflater = LayoutInflater.from(customContext);

(抱歉在尽我所能之前询问)。

您可以使用这个简单的 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);
    }
}

然后像那样使用它

Context localizedContext = LocalizedContextWrapper.wrap(context, locale);