Android中如何基于自定义Locale填充视图生成发票收据Bitmap?
基于自定义Locale填充LayoutInflater视图的解决方案
我来帮你搞定自定义Locale填充视图的问题!这里有两个实用的方案,你可以根据自己的场景选择:
方案1:创建带自定义Locale的ContextWrapper(全局适配)
这个方案适合你需要整个发票布局都按照自定义Locale显示(比如字符串、日期格式、数字格式全适配)的场景。核心思路是先包装一个带有目标Locale的Context,再用这个Context获取LayoutInflater,这样inflate出来的视图会自动使用该Locale的资源。
步骤1:实现ContextWrapper类
public class CustomLocaleContextWrapper extends ContextWrapper { public CustomLocaleContextWrapper(Context base, Locale customLocale) { super(base); // 更新资源配置 Resources resources = getResources(); Configuration configuration = resources.getConfiguration(); // 针对不同Android版本处理Locale设置 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { configuration.setLocale(customLocale); configuration.setLocales(new LocaleList(customLocale)); createConfigurationContext(configuration); } else { configuration.locale = customLocale; resources.updateConfiguration(configuration, resources.getDisplayMetrics()); } } // 静态方法简化创建 public static ContextWrapper wrap(Context context, Locale customLocale) { return new CustomLocaleContextWrapper(context, customLocale); } }
步骤2:在现有代码中替换Context
把原来获取LayoutInflater的代码改成用包装后的Context:
// 定义你的目标Locale,比如土耳其语(tr_TR)或者自定义的Locale Locale customLocale = new Locale("tr", "TR"); // 包装原始Context Context wrappedContext = CustomLocaleContextWrapper.wrap(getContext(), customLocale); // 用包装后的Context获取LayoutInflater LayoutInflater inflater = LayoutInflater.from(wrappedContext); View view = inflater.inflate(R.layout.layout_invoice, null); // 后续的视图填充、测量生成Bitmap的代码保持不变 int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(paperWidth, View.MeasureSpec.EXACTLY); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(widthMeasureSpec, heightMeasureSpec); // ... 继续生成Bitmap的逻辑
方案2:手动加载指定Locale的资源(局部适配)
如果只是需要修改布局中部分字符串/资源,不想全局修改Context的Locale,可以直接针对自定义Locale加载资源:
// 定义目标Locale Locale customLocale = new Locale("tr", "TR"); // 获取原始Resources Resources resources = getContext().getResources(); Configuration config = new Configuration(resources.getConfiguration()); config.setLocale(customLocale); // 创建临时Resources对象加载指定Locale的资源 Resources customResources = getContext().createConfigurationContext(config).getResources(); // 比如加载对应Locale的发票标题字符串 String invoiceTitle = customResources.getString(R.string.invoice_title); // 然后手动设置到TextView上 TextView titleTv = view.findViewById(R.id.tv_invoice_title); titleTv.setText(invoiceTitle); // 其他需要适配的资源同理处理...
额外提示
- 如果你需要处理日期、数字这类格式化内容,记得用自定义Locale初始化
SimpleDateFormat或NumberFormat,比如:SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy", customLocale); String formattedDate = dateFormat.format(new Date()); - 对于Android 8.0及以上版本,Locale的设置API有变化,方案1的代码已经做了兼容处理。
内容的提问来源于stack exchange,提问作者Heysem Katibi
相关产品推荐
相关产品推荐

