在android editText上使用分数

时间:2013-06-10 23:10:00

标签: android eclipse android-edittext

我想在编辑文本中输入一个inputType,我可以像这样输入小数:2/4(我想打印“/”)。 该程序是关于计算的东西,我需要输入小数的分数。谢谢。对不起我的英文不好。

2 个答案:

答案 0 :(得分:0)

我认为最好的方法是使用字符串作为输入文本,然后解析字符串以确定用户输入的内容。

当用户完成输入后,您可以使用以下内容检查字符串:

public float testInputString(String testString) {
    boolean goodInput = true;
    float result = 0;
    if (testString.contains("/")) {
        //possible division
        String pieces[] = testString.split("/");
        if (pieces.length != 2) {
            goodInput = false;
        } else {
            try {
                float numerator = Float.parseFloat(pieces[0]);
                float denominator = Float.parseFloat(pieces[1]);
                result = numerator/denominator;
            } catch (Exception e) {
                goodInput = false;
            }
        }
    }  else if (testString.contains(".")) {
        try {
            result = Float.parseFloat(testString);                
        } catch (Exception e) {
            goodInput = false;
        }
    }

    //TODO something here if bad input, maybe an alert or something
    return result;
}

此外,如果您使用keylistener like this,则可以在键入有效输入时进行检查。您可以修改它以仅允许数字。和/.

答案 1 :(得分:-1)

将此属性放在Edittext的xml节点中,并使用Double表示法而不是“/”

android:digits="1234567890.-"