我创建了一个旋转器,显示了世界上所有国家的名称。现在,我想通过从Spinner选择该物品时将像AFG这样的价值用于阿富汗,意大利的ITA等,以作为字符串存储。我对如何做这件事感到困惑。由于,我将在Spinner中分配全名,并希望通过单击旋转器时传递与国家名称不同的数据(就像我对意大利所说的意大利所说的那样)。
创建对象pojo喜欢
class Country{
String name;
String code;
//getter and setters
}
和设置国家清单 List<Country> list;
到适配器
显示country 名称和访问country 代码
spinner.getSelectedItem().getCode();
这可以为两件事做,一件如果您想在代码中使用但不想在选择其他名称中查看,第二个是您想在Spinner和Spinner中显示名称在下面的代码检查中使用。
创建一个通用类,用于存储
之类的国家名称和国家代码commonClass.java
//I am taking it as CommonClass you can change it.
public static final String[] strCountryNames = {"India","Italy","Afghanistan","United States of America"};
public static final String[] strCountryCodes = {"IND","ITA","AFG","USA"};
现在,对于旋转器setaDapter,使用commonclass.strcountrynames,
以及您要在哪里使用代码的地方使用commonClass.strcountrycode,
假设您想获得印度的代码,然后可以将其检查为
CommonClass.strCountryCode[spinner.selectyedPosition];
而不是传递完整的国家名称,您可以获取选定的国家并致电str.substring(0, 3).toUpperCase()
如果您想要前三个名称
String countryName = "China"
String shortName = countryName.substring(3).toUpperCase();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int pos = spinner.getSelectedItemPosition();
String mysourcestring= yourarraylistname[+pos];
String substr=mysourcestring.substring(0,3).toUpperCase();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
现在,您要通过的价值将在substr中。对不起,如果有任何错误,希望这有帮助