如何将多个微调器相加?

时间:2016-04-14 08:31:12

标签: java string android-studio sum spinner

我有多个带有字符串数组的微调器,其中有3个项目称为" 70"," 80"和" 90"。在用户选择这些不同的微调器项之后,我希望能够总结用户已选择的所有项并在文本视图中显示总数。例如,用户选择" 70"来自一个旋转器" 70"从另一个,textview将显示总数140.我怎么能这样做?

public class FragmentCalc3 extends Fragment{

Context context;
TextView Results;







public static FragmentCalc3 newInstance()
{
    FragmentCalc3 fragment = new FragmentCalc3();
    return fragment;
}
public FragmentCalc3() {}
// Required empty public constructor

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_calculator3, container, false);
    Results = (TextView) rootView.findViewById(R.id.Results);



    context = container.getContext();

    final Spinner spinner1 = (Spinner) rootView.findViewById(R.id.TestSpinner2);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
    spinner1.setAdapter(adapter1); // Apply the adapter to the spinner

    final Spinner spinner2 = (Spinner) rootView.findViewById(R.id.TestSpinner1);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(context, R.array.GradeTest, android.R.layout.simple_spinner_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears
    spinner2.setAdapter(adapter2); // Apply the adapter to the spinner

    spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


            int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString());
            int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
            int Results = spinner2Value + spinner1Value;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });








    return rootView;
}

}

1 个答案:

答案 0 :(得分:0)

如果您有两个微调器spinner2spinner1,并且您希望在选择spinner2项时获得结果,那么只需这样做,

spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        int spinner2Value = Integer.parseInt(spinner2.getSelectedItem().toString()); //Add try catch block if necessary
        int spinner1Value = Integer.parseInt(spinner1.getSelectedItem().toString());
     int yourResult = spinner2Value + spinner1Value; //Result
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
     //Do nothing
    }

});