我试图通过从微调器中选择一个国家来填充城市。它应该根据第一个微调器的选择填充第二个微调器的内容。我的strings.xml和MainActivity.java文件是这样的:
的strings.xml
<!-- Countries -->
<string-array name="country_names">
<item>Turkey</item>
<item>Spain</item>
</string-array>
<!-- Cities -->
<string-array name="Turkey">
<item>Istanbul</item>
<item>Adana</item>
</string-array>
<string-array name="Spain">
<item>Madrid</item>
<item>Barcelona</item>
</string-array>
MainActivity.java
citySpinner = (Spinner) findViewById(R.id.input_city);
countrySpinner = (Spinner) findViewById(R.id.input_country);
countryAdapter = ArrayAdapter.createFromResource(this,R.array.country_names,android.R.layout.simple_spinner_item);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
final String[] country = new String[1];
countrySpinner.setAdapter(countryAdapter);
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
country[0] = adapterView.getItemAtPosition(i).toString();
Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView)
{
}
});
cityAdapter = ArrayAdapter.createFromResource(this,R.array.Turkey,android.R.layout.simple_spinner_item);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(cityAdapter);
我需要在cityAdapter = ArrayAdapter.createFromResource(...)
行内提供一个变量,而不是写土耳其语或任何国家/地区名称。
我无法在网上找到任何有用的内容,这是我最后的希望:)
答案 0 :(得分:0)
在第一个微调器的setonitemselected中,声明第二个微调器并调用clicklistener函数,即second_spinner.setonitemselectedlistener,然后两个回调方法将在第一个微调器的setonitemselected方法中实现。
答案 1 :(得分:0)
试试这个:
countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
country[0] = adapterView.getItemAtPosition(i).toString();
Toast.makeText(mContext, adapterView.getItemAtPosition(i) + " selected", Toast.LENGTH_SHORT).show();
switch (i) {
case 0:
cityAdapter = ArrayAdapter.createFromResource(this, R.array.Turkey, android.R.layout.simple_spinner_item);
break;
case 1:
cityAdapter = ArrayAdapter.createFromResource(this, R.array.Madrid, android.R.layout.simple_spinner_item);
break;
}
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
citySpinner.setAdapter(cityAdapter);
}
@Override
public void onNothingSelected (AdapterView < ? > adapterView)
{
}
});