2016-03-25 7 views
0

1つの入力から複数の変数(int、double、String)を読み込もうとしています。しかし、入力は特定の方法でなければならない。すなわち、ユーザは、「Xマイル」(小数または整数のいずれか)または「Y分」(整数のみ)を入力することによって、マイル単位で距離を入力する必要がある。ここに私がコード化したものの例があります。ただし、ダブルを入力しても機能しません。他の方法でもこれらの値を使用する必要があります。1つの文字列入力から複数の変数を読み取るAndroidアプリ

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; 
} 
+0

だから、あなたは何をしたいですか?あなたのトラブルは何ですか? –

+0

私はそれを確認し、ユーザーが正しいint/doubleとStringを入力しているかどうかを確認したいと思います。そうでない場合は、AlertDialogをスローしたいと思います。たとえば、ユーザーが入力として「12.5分」と入力すると、12.5が整数ではないためAlertDialogがスローされます。 – AnyMoose72

+0

私は@Phoenixがあなたの要件に応じて正解を持っていると思っていますが、警告ダイアログを表示するタイミングを知るアルゴリズムは間違いなく改善できます。どのように知りたいですか?コメントを削除します。 :) –

答えて

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 
      } 
     }); 
関連する問題