Android Spinner:如果用户根据CURRENT时间选择前一小时或分钟,则显示toast

时间:2014-03-21 11:48:32

标签: android datetime datepicker android-spinner

我有两个id为hhmm的微调器以及全局数组列表

String[] pickup_hour = { "HH", "00", "01", "02", "03", "04", "05", "06",
        "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17",
        "18", "19", "20", "21", "22", "23" };

String[] pickup_min = { "MM", "00", "05", "10", "15", "20", "25", "30",
        "35", "40", "45", "50", "55" };

Spinner pickup_hour:

sp3 = (Spinner) findViewById(R.id.hh);

    sp3.setOnItemSelectedListener(new OnItemSelectedListener() {
        Calendar c1 = Calendar.getInstance(); 


        int hour = c1.get(Calendar.HOUR_OF_DAY);

        @Override
        public void onItemSelected(AdapterView<?> parent, View v,
                int position, long id) {

            edsp3.setText(pickup_hour[position]);


                         if(position<hour)
                         {
                             Toast.makeText(OnlineBooking.this, "Choose greater hour",
                                        Toast.LENGTH_LONG).show();

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

        }
    });
    ArrayAdapter b3 = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, pickup_hour);

    b3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp3.setAdapter(b3);

Spinner pickup_min:

sp4 = (Spinner) findViewById(R.id.mm);
    sp4.setOnItemSelectedListener(new OnItemSelectedListener() {

        Calendar c2 = Calendar.getInstance();
        int minutes = c2.get(Calendar.MINUTE);
        @Override
        public void onItemSelected(AdapterView<?> parent, View v,
                int position1, long id) {
            Log.d("bbb", ""+minutes);
            edsp4.setText(pickup_min[position1]);

             if (position1<minutes){
                 Toast.makeText(OnlineBooking.this, "Choose greater minutes",
                            Toast.LENGTH_LONG).show();
             }}

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

        }
    });
    ArrayAdapter b4 = new ArrayAdapter(this,
            android.R.layout.simple_spinner_item, pickup_min);

    b4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp4.setAdapter(b4);

问题:如果用户根据CURRENT时间选择任何前一小时和任何前一分钟,我正在尝试显示Toast。我的代码没有用完。

我如何解决这个问题并实现目标?

提前致谢。

1 个答案:

答案 0 :(得分:1)

你的条件是:

 if(position<hour)
                     {
                         Toast.makeText(OnlineBooking.this, "Choose greater hour",
                                    Toast.LENGTH_LONG).show();

    }

将其更改为:

 String hourSelected = pickup_hour[position];
 if(Integer.parseInt(hourSelected)<hour)
                     {
                         Toast.makeText(OnlineBooking.this, "Choose greater hour",
                                    Toast.LENGTH_LONG).show();

    }

使用Integer.parseInt时确保位置不是== 0,因为如果选择了HH,它将抛出UnSupportedNumberFormat异常。