我保存用户选择,并希望在用户恢复活动时通过自动选择微调器项目来显示用户选择的项目。
TypesCustomArrayAdapter
public class TypesCustomArrayAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final Context mContext;
private final List<TypesSpinnerItemObject> items;
private final int mResource;
public TypesCustomArrayAdapter(@NonNull Context context, @LayoutRes int resource,
@NonNull List objects) {
super(context, resource, 0, objects);
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = resource;
items = objects;
}
@Override
public View getDropDownView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
return createItemView(position, convertView, parent);
}
@Override
public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return createItemView(position, convertView, parent);
}
private View createItemView(int position, View convertView, ViewGroup parent){
final View view = mInflater.inflate(mResource, parent, false);
TextView txtName = (TextView) view.findViewById(R.id.name);
TextView txtId = (TextView) view.findViewById(R.id.code);
TypesSpinnerItemObject item = items.get(position);
txtName.setText(item.Name);
txtId.setText(item.Id);
return view;
}
我如何填充微调器
ArrayAdapter vaziatSokonatAdapter = TypesCustomArrayAdapter(VillageInputActivity.this, R.layout.item_types_spinner, response.body());`
保存用户选择:
Object ss = mySpinner.getSelectedItem();
Gson gson = new Gson();
String json = gson.toJson(ss);
SharedPreferences.Editor editor = getSharedPreferences("ss", MODE_PRIVATE).edit();
editor.putString("ss", json);
editor.apply();
我如何尝试更改微调器的选定项目:
SharedPreferences sh = getSharedPreferences("ss", MODE_PRIVATE);
String ss= sh.getString("ss", "");
Gson gson = new Gson();
Object ss = gson.fromJson(ss, mySpinner.getSelectedItem().getClass());
mySpinner.setSelection(vaziatSokonatAdapter.getPosition(ss));
但是vaziatSokonatAdapter.getPosition(ss)返回-1