在我的测试Android项目中,我使用了StringArray resource的以下语言:
<resources>
<string-array name="ueTTSLangSelectorSpinnerValues">
<item>
English
</item>
<item>
Deutsch
</item>
<item>
Français
</item>
<item>
Italiano
</item>
</string-array>
</resources>
,它正在提供Spinner语言选择器。因此,当用户选择语言时,我需要找到对应语言的Locale:
m_ueLangSelectorSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id)
{
// language has been selected, search for its VALID locale and prepare found locale for Text to Speech engine
int ueSelectedLanguageIndex=m_ueLangSelectorSpinner.getSelectedItemPosition(); // get selected language index
if(((ueSelectedLanguageIndex>=0)&&(ueSelectedLanguageIndex<m_ueLangSelectorSpinner.getCount())))
{
// selected language index is valid, fetch it
String ueSelectedLanguage=m_ueAvailableLanguages[ueSelectedLanguageIndex];
Locale ueSelectedLocale=Locale.forLanguageTag(ueSelectedLanguage);
} // if
} // onItemClick
});
,但是我得到了无效/空的语言环境。为什么?
答案 0 :(得分:1)
看看forLanguageTag
的{{3}},我认为您的问题是格式错误的语言标签,您不能只使用“英语”和“德语”作为语言标签,正确的标签应该是“ zh-cn”之类的标签或类似的标签(有关详细信息,请参阅文档)
答案 1 :(得分:0)
我找到了一种选择语言的方法(将String中的Spinner还原为前两个字符,然后将其小写。结果为ISO 639-2 language code,可以将其传递给以下一种语言Locale's constructor:
m_ueLangSelectorSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
/**
* @brief Spinner selection click handler
* @param parent
* @param view
* @param position
* @param id
*/
@Override
public void onItemSelected(AdapterView<?> parent,
View view,
int position,
long id)
{
// Language has been selected, search for its VALID locale and prepare found locale for Text to Speech engine
int ueSelectedLanguageIndex=m_ueLangSelectorSpinner.getSelectedItemPosition(); // get selected language index
String ueSelectedLanguage; // selected language
String ueTTSSpeakButtonText; // speak button text for selected language
m_ueTTSTextEntryField.setText(""); // on language change, clear text
m_ueTTSTextEntryField.setEnabled(false); // disable button since text is empty
m_ueTTSTextEntryField.setClickable(false); // disables button clicking since text is empty
if(((ueSelectedLanguageIndex>=0)&&(ueSelectedLanguageIndex<m_ueLangSelectorSpinner.getCount())))
{
// Selected language index is valid, fetch it and transforms it to locale name
ueSelectedLanguage=m_ueAvailableLanguages[ueSelectedLanguageIndex]; // get selected language name
if(ueSelectedLanguage.length()>=2)
{
// Size of selected language string is ok, transform it to locale name and create locale object
ueTTSSpeakButtonText=m_ueAvailableTTSSpeakButtonTexts[ueSelectedLanguageIndex]; // get speak button text
m_ueTSSSpeakButton.setText(ueTTSSpeakButtonText); // update button "speak" text
m_ueSelectedLanguageLocale=new Locale(ueSelectedLanguage.substring(0,
2).toLowerCase()); // creates locale
} // if
} // if
} // onItemSelected