在Android中使用自定义语言环境膨胀视图

5

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

但是由于某种原因它不能工作。任何帮助都将不胜感激。


你尝试过这个SO吗? - Sagar
1
在我的情况下,没有要调用recreate()的活动,而且我不想更改应用程序的语言环境,我只想以自定义语言环境填充特定视图。 - Heysem Katibi
我正在膨胀视图并绘制它,甚至没有在屏幕上显示它。 - Heysem Katibi
2个回答

6
你可以使用这个简单的类创建本地化上下文。
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);

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

(抱歉在尽力之前就提问了)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接