使用textwatcher进行Editext日期验证

时间:2013-11-20 23:54:30

标签: android textwatcher

我正在尝试编写一个验证android中输入日期的textwatcher。我的textwatcher代码如下:

idate.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }
        @Override
        public void afterTextChanged(Editable s) {
            // set oid value now
            try{                        
            EditText idate = (EditText)findViewById(R.id.pDate); //initial date
            EditText fdate = (EditText)findViewById(R.id.SDate); //final date
            iniDate= s.toString();
            EditText inNDF = (EditText)findViewById(R.id.NDF);  //numberofdays
            inndf= Integer.parseInt(inNDF.getText().toString());
            CullCowintro cfo= new CullCowintro();
            cfo.setDate();               //calculate final date
            fdate.setText((sDate.get(Calendar.MONTH)) + "/" + 
                    sDate.get(Calendar.DAY_OF_MONTH) + "/" +
                    sDate.get(Calendar.YEAR));
            fdate.setKeyListener(null);        
            startmonth = (pDate.get(Calendar.MONTH));
            endmonth = (sDate.get(Calendar.MONTH));   

      }             
            catch(NumberFormatException e){}
            }

    });

我的setDate()函数如下:

public void setDate()
{
    pDate = new GregorianCalendar();
    sDate = new GregorianCalendar();
    String date[] = iniDate.split("/", 3);

    try{
        month = Integer.parseInt(date[0])-1;
        if(month < 0 || month > 11)
        throw new NumberFormatException();
        day = Integer.parseInt(date[1]);
        if(day < 1 || day > 31)
        throw new NumberFormatException();
        year = Integer.parseInt(date[2]);
        if(year < 100)
        year += 2000;
        pDate.clear();
        pDate.set(year, month, day); 
        sDate.clear();
        sDate.set(year, month, day);
        sDate.add(Calendar.DAY_OF_MONTH,inndf);

    }
    catch(NumberFormatException e){
    Toast.makeText(getBaseContext(),"Please enter the date as mm/dd/yyyy.", Toast.LENGTH_SHORT).show();
    }
    }
//  return initSDate;
}

然而,当我输入无效日期时,应用程序只是崩溃而不是转到nfe并打印toast消息。我做错了什么?

0 个答案:

没有答案