You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

hbb20 CountryCodePicker土耳其语Locale下部分国旗不显示问题求助

问题描述

在Android应用中使用hbb20的CountryCodePicker库时,碰到了国旗显示异常的问题:

  • 应用支持英语、土耳其语双语言,配有独立的字符串资源文件
  • 当应用Locale切换为土耳其语(tr)时,部分国家的国旗无法正常显示
  • 试过临时把Locale改成英语再恢复,但这属于临时 workaround,不是合理的解决方案

对应的布局代码:

<com.hbb20.CountryCodePicker
    android:id="@+id/ccp"
    app:ccpDialog_showFlag="true"
    android:layout_width="wrap_content"
    android:layout_height="45dp"
    android:background="@drawable/edittxt_bg"
    app:ccp_autoFormatNumber="false"
    app:ccp_countryPreference="TR,IN,GY"
    app:ccp_hintExampleNumber="true"
    app:ccp_hintExampleNumberType="MOBILE"
    app:ccp_showFullName="false"
    app:ccp_showPhoneCode="false"
    app:ccp_defaultNameCode="TR"/>

业务逻辑代码:

ccp = findViewById(R.id.ccp);
ccp.registerCarrierNumberEditText(userID);
ccp.setDefaultCountryUsingNameCode("TR");

System.out.println("countryCode: " + countryCode);

LoadLocale.load(MainActivity.this);

// 保存当前语言用于后续恢复
SelectedLanguage = getLanguage(MainActivity.this);
Log.d("LangCheck", "choosenlanguage: " + SelectedLanguage);

// 临时切换到英语以显示国旗
LoadLocale.set(MainActivity.this, "en");

ccp.setNumberAutoFormattingEnabled(false);

ccp.setOnCountryChangeListener(() -> {
    countryCode = ccp.getSelectedCountryCode();
    String countryName = ccp.getSelectedCountryName();
    Log.d("CountryCodePicker", "Selected country code: " + countryCode + ", name: " + countryName);
});
解决方案

方法1:给CCP单独设置固定Locale

这个库的国旗加载会受当前Context的Locale影响,你可以为CCP创建一个独立的Context,强制用英语Locale加载国旗,不影响应用整体的语言设置:

// 创建使用英语Locale的配置
Configuration config = new Configuration(getResources().getConfiguration());
config.setLocale(Locale.ENGLISH);
Context ccpContext = createConfigurationContext(config);

// 用这个独立Context初始化CCP
ccp = ccpContext.findViewById(R.id.ccp);
// 后续的CCP初始化逻辑不变
ccp.registerCarrierNumberEditText(userID);
ccp.setDefaultCountryUsingNameCode("TR");

方法2:补充土耳其语资源目录的国旗文件

部分国旗不显示可能是因为res/drawable-tr/目录下缺少对应的国旗图片,检查该目录是否存在所有需要的国旗Drawable,如果缺失,直接从默认的res/drawable/目录复制对应的文件到drawable-tr目录下即可。

方法3:修改库的国旗加载逻辑(适用于可以自定义库源码的场景)

如果你能修改库的源码,找到加载国旗的相关代码,将加载时使用的Locale固定为英语,避免受应用Locale影响。比如在加载国旗Drawable的代码中,明确指定Locale:

// 示例:修改库中加载国旗的代码段
Locale fixedLocale = Locale.ENGLISH;
Configuration resConfig = new Configuration(getResources().getConfiguration());
resConfig.setLocale(fixedLocale);
Resources fixedRes = createConfigurationContext(resConfig).getResources();
Drawable flag = fixedRes.getDrawable(fixedRes.getIdentifier("flag_" + countryCode, "drawable", getPackageName()));

内容的提问来源于stack exchange,提问作者Joy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:13:10