其他分享
首页 > 其他分享> > 在Android中使用自定义语言环境扩展视图

在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

但是由于某种原因,它不起作用.任何援助将不胜感激.

解决方法:

您可以使用此简单的类创建本地化的上下文

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);

标签:layout-inflater,locale,android
来源: https://codeday.me/bug/20191109/2011224.html