我想做一个简单的本地化演示,我有一个微调器来选择语言和一个文本视图来显示所需语言的字符串,这是我的代码
public class MainActivity extends Activity implements OnItemSelectedListener
{
Spinner laguageSpinner;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
laguageSpinner = laguageSpinner = ((Spinner) findViewById(R.id.spinner1));
laguageSpinner.setOnItemSelectedListener(this);
generateLanguageItems();
}
public void generateLanguageItems()
{
laguageSpinner = laguageSpinner = ((Spinner) findViewById(R.id.spinner1));
List<String> list = new ArrayList<String>();
list.add("English");
list.add("عربي");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
R.layout.el_spinner_txtview, list);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
laguageSpinner.setAdapter(dataAdapter);
}
@Override
public void onItemSelected(AdapterView<?> adapter, View arg1, int pos,
long arg3)
{
Toast.makeText(this, adapter.getItemAtPosition(pos) + "",
2000).show();
switch(pos)
{case 0: changeLocale( "en" );break;
case 1: changeLocale( "ar" );break;}
}
public void changeLocale( String code )
{
Locale locale = new Locale(code);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
this.setContentView(R.layout.activity_main);
generateLanguageItems();
}
}
本地化更改代码完美运行,我已经通过更改它进行了测试
switch(pos)
{case 0: changeLocale( "en" );break;
case 1: changeLocale( "ar" );break;}
到那个
switch(pos)
{case 0: changeLocale( "ar" );break;
case 1: changeLocale( "en" );break;}
我的问题是在运行时不再生成微调器项目我有一个空微调器,试图对代码进行一些更改但没有运气,你能帮我吗?
---编辑--- 事实上我试过这样做
public void generateLanguageItems()
{
....
laguageSpinner = ((Spinner) findViewById(R.id.spinner1));
laguageSpinner.setAdapter(dataAdapter);
}
这种方式微调项目确实生成但onItemSelected()
不会再触发,然后我添加了
public void generateLanguageItems()
{
...
laguageSpinner.setOnItemSelectedListener(null);
laguageSpinner = ((Spinner) findViewById(R.id.spinner1));
laguageSpinner.setAdapter(dataAdapter);
laguageSpinner.setOnItemSelectedListener(this);
}
现在它会递归触发,我无法单击微调器并为其项目充气!