【问题标题】:Inflating a view with custom locale in Android在 Android 中使用自定义区域设置膨胀视图
【发布时间】:2018-05-04 15:32:29
【问题描述】:

我正在使用 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 吗?
  • 在我的情况下,没有可以调用 recreate() 的活动,另外我不想更改应用程序的语言环境,我只想在自定义语言环境中扩展该特定视图。
  • 我正在放大视图并绘制它,甚至没有在屏幕上显示它。

标签: android locale layout-inflater


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    Configuration config = new Configuration(resources.getConfiguration());
    Context customContext = context.createConfigurationContext(config);
    
    Locale newLocale = new Locale("fr");
    config.setLocale(newLocale);
    
    LayoutInflater inflater = LayoutInflater.from(customContext);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      相关资源
      最近更新 更多