我正在制作一个Android应用程序,要求用户通过微调框选择国家和城市。
首先,我像这样从json获取数据:
String state = json.data.getState();
String city = json.data.getCity();
当用户第一次打开应用程序时,微调器的值为String state和String city,这是我的代码:
final List<State> statesList = new ArrayList<>();
final List<String> states = new ArrayList<>();
final StateAdapter stateAdapter = new StateAdapter(this,
R.layout.state_list, R.id.spinnerText, statesList);
SpinnerCity.setAdapter(stateAdapter);
SpinnerCity.setSelect(String state); //????
SpinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State cityDetails = stateAdapter.getItem(position);
List<String> cityList = cityDetails.getCities();
ArrayAdapter citiesAdapter = new ArrayAdapter<>(this,
R.layout.city_list, R.id.citySpinnerText, cityList);
SpinnerArea.setAdapter(citiesAdapter);
SpinnerArea.setSelected(String city); //???
}
class StateAdapter extends ArrayAdapter<State> {
private List<State> stateList = new ArrayList<>();
public StateAdapter(@NonNull Context context, int resource, int spinnerText, @NonNull List<State> stateList) {
super(context, resource, spinnerText, stateList);
this.stateList = stateList;
}
@Override
public State getItem(int position) {
return stateList.get(position);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull
ViewGroup parent) {
return initView(position);
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return initView(position);
}
private View initView(int position) {
State state = getItem(position);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.state_list, null);
TextView textView = view.findViewById(R.id.spinnerText);
textView.setText(state.getStateName());
return view;
}
我只是不知道首先如何将String放在Spinner中? 顺便说一句,用户还可以通过微调器更改州和城市, 我将更改信息保存到对象中。谢谢。
[编辑] 我知道如何setSelection,例如:
int position = stateAdapter.getPosition(statesList.get(3));
stateSpinner.setSelection(position);
如果我得到json的数据是String,我怎么知道StatesList.get(?)
奇怪?当我得到String“ Kaohsuing”时,我尝试在ArrayList中找到位置,但是我总是得到-1,这意味着String与Arraylist数据不匹配。
我的错误,如果我想找到状态position,解决方法是:
List<String> states = new ArrayList<>();
int cityPosition = states.indexOf(City);
SpinnerCity.setSelection(cityPosition);
答案 0 :(得分:0)
首先,您需要获取适配器内物品的位置
int vPos = stateAdapter.getPosition("myStringValue");
然后您可以设置默认值
SpinnerCity.setSelection( vPos );
祝你好运!
答案 1 :(得分:0)
最简单的方法是通过state
值从适配器中获取状态的位置。
例如:
int position = stateAdapter.getPosition(state);
SpinnerCity.setSelection(position)
要使其正常工作,状态和适配器中的值应相等。 如果它们不相等,则位置将无法正确返回。
答案 2 :(得分:0)
您无法使用自定义模型类的arraylist设置Spinner适配器 类型,列出statesList。
str_replace
Instead set adapter with List<String>:
List<String> stateNames = new ArrayList();
add stateName to the above arrayList from statesList;
Set this arrayList to state Spinner as Adapter.