Android应用程序从一个String输入读取多个变量

时间:2016-03-25 15:38:01

标签: java android input

我试图从一个输入中读取多个变量(int,double,String)。然而,输入必须是特定的方式,即用户应通过输入“X英里”(小数或整数)或时间输入“Y分钟”(仅作为整数)输入距离(英里)。这是我编码的一个例子。但是,输入double不起作用。我还需要在其他方法中使用这些值。

    public boolean hintWalkTracker() {
    // tracks whether the input for walking/running activity is correct
    String text = String.valueOf(hintEditText.getText());
    String s = text.replaceAll("\\d","");
    int i = Integer.parseInt(text.replaceAll("[\\D]", ""));
    double d = Double.parseDouble(text.replaceAll("[\\D]", ""));

    if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running"))  && s.equals(" miles")) {
        d = d * 88.9;
        return true;
    } else if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running")) && s.equals(" mins")) {
        d = i * 4.78;
        return true;
    } else if ((activityDropDown.getSelectedItem().equals("Walking") || activityDropDown.getSelectedItem().equals("Running")) && ((!s.equals(" mins")) || !s.equals(" miles"))) {
        // create a new AlertDialog Builder
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        // set dialog's message to display
        builder.setMessage(R.string.walk_missing_message);

        // provide an OK button that simply dismisses the dialog
        builder.setPositiveButton(R.string.OK, null);

        // create AlertDialog from the AlertDialog.Builder
        AlertDialog errorDialog = builder.create();
        errorDialog.show(); // display the modal dialog
        return false;
    }
    return false;
}

1 个答案:

答案 0 :(得分:1)

您只需在EditText上使用TextWatcher即可检查用户正在撰写的内容,并在撰写您需要的内容时根据需要做出反应。

代码示例:

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

                // TODO Auto-generated method stub
                hintWalkTracker();
            }

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

                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {

                // TODO Auto-generated method stub
            }
        });