嗨我创建了两个微调器,我给两个微调器提供了两个不同的默认值,但它只取一个值作为默认值,如果我只设置fromtext或totext它正确,当我设置它没有采取。我不明白故障发生在哪里。
public class UniqueConverter extends Fragment {
private Spinner fromDetails, toDetails;
private EditText fromInput, toInput;
public static UniqueConverter setArguments(int position) {
UniqueConverter uniqueConverter = new UniqueConverter();
Bundle args = new Bundle();
args.putInt("position", position);
uniqueConverter.setArguments(args);
return uniqueConverter;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_uniquelayout, container, false);
int position = getArguments().getInt("position");
onInitVies(view);
switch (position) {
case 0:
setAdapter(getResources().getStringArray(R.array.temperatureform), "Celsius", "Fahrenheit");
break;
case 1:
setAdapter(getResources().getStringArray(R.array.weightform), "Kilograms", "Grams");
break;
return view;
}
private void setAdapter(String[] spinnerItems, String fromDefaultText, String toDefaultText) {
fromDetails.setAdapter(new CustomSpinnerAdapter(getContext(), R.layout.spinner_item, spinnerItems, fromDefaultText));
toDetails.setAdapter(new CustomSpinnerAdapter(getContext(),R.layout.spinner_item,spinnerItems,toDefaultText));
}
private void onInitVies(View view) {
fromDetails = (Spinner) view.findViewById(R.id.fromSpinner);
toDetails = (Spinner) view.findViewById(R.id.toSpinner);
fromInput = (EditText) view.findViewById(R.id.fromInput);
toInput = (EditText) view.findViewById(R.id.toInput);
}
}
我的字符串数组:
<string-array name="temperatureform">
<item name="c">Celsius</item>
<item name="f">Fahrenheit</item>
<item name="k">Kelvin</item>
</string-array>
spinnerAdapter:
public class CustomSpinnerAdapter extends ArrayAdapter<String> {
Context context;
String[] objects;
String firstElement;
boolean isFirstTime;
public CustomSpinnerAdapter(Context context, int textViewResourceId, String[] objects, String defaultText) {
super(context, textViewResourceId, objects);
this.context = context;
this.objects = objects;
this.isFirstTime = true;
setDefaultText(defaultText);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if (isFirstTime) {
objects[0] = firstElement;
isFirstTime = false;
}
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
notifyDataSetChanged();
return getCustomView(position, convertView, parent);
}
public void setDefaultText(String defaultText) {
this.firstElement = objects[0];
objects[0] = defaultText;
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.spinner_item, parent, false);
TextView label = (TextView) row.findViewById(R.id.text1);
label.setText(objects[position]);
return row;
}
}