Android检查文本输入(时间)是否与格式

时间:2017-10-05 10:11:41

标签: android time kotlin

我有两个文本字段作为输入时间(mm:ss) 如何创建支票(使用Toast,我知道如何制作吐司xD)以查看它是否与该格式匹配,如果没有,则传递给吐司?一直在尝试,但没有管理任何事情。

我不知道你是否需要更多,但这是我传递它们的地方:

val time = findViewById<NumberPicker>(R.id.time) as TextView
    val distance = findViewById<NumberPicker>(R.id.distance) as TextView
    val pace = findViewById<NumberPicker>(R.id.pace) as TextView


    calculate.setOnClickListener {

        when {

            time.text.isEmpty() && (distance.text.isNotEmpty() && pace.text.isNotEmpty()) -> calculatePace(null, distance.text.toString(), pace.text.toString())

            distance.text.isEmpty() && (time.text.isNotEmpty() && pace.text.isNotEmpty()) -> calculatePace(time.text.toString(), null, pace.text.toString())

            pace.text.isEmpty() && (time.text.isNotEmpty() && distance.text.isNotEmpty()) -> calculatePace(time.text.toString(), distance.text.toString(), null)

            else -> {
                Toast.makeText(this, "Please check all fields", Toast.LENGTH_SHORT).show()
            }
        }
    }

这样就够了,还是需要我使用它的功能? 谢谢

======

修改

我尝试创建此功能但是如何在此处传递我的编辑分机?它也是正确的吗?

fun isTimeValid(time: String?): Boolean {
    val expression = "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\$"
    val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
    val matcher = pattern.matcher(time)
    return matcher.matches()
}

1 个答案:

答案 0 :(得分:0)

试试这个。

 if (!Constants.isStringEmpty(str_time)&&isTimeValid(str_time)){
        //// TODO: 10/6/2017  
    }else {
        if (Constants.isStringEmpty(str_time)){
            edt_email.requestFocus();
            Toast.makeText(this, "Enter Time.", Toast.LENGTH_SHORT).show();
        }
        else if(!isTimeValid(str_time)){
            edt_email.requestFocus();
            Toast.makeText(this, "Enter Valid Time.", Toast.LENGTH_SHORT).show();
        }
    }

 public static boolean isTimeValid(String time) {
    boolean isValid = false;
    String expression = "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$";
    CharSequence inputStr = time;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
 }