[英]Android (Java) Real-time Audio Input (microphone AND USB) and Output
[英]Filter Input in Real-Time?
我有一個帶有偵聽器的EditText(接受0-9)。 我想在輸入時抓取輸入,應用計算,並將其顯示在同一EditText框中。
框最初顯示$ 0.00。 當用戶輸入2時,我想從框中獲取它,解析它以除去$和十進制,將其轉換為int ...除以100,然后在其前面加上$。 在setText之后,它應該顯示$ 0.02。 如果他們再按5,我將抓住它,解析它,最后得到25,進行數學運算,它應該顯示$ 0.25,依此類推。
我不知道這是否是最好的方法,我願意接受新想法。 這是我當前的代碼:
mEditPrice.addTextChangedListener(new TextWatcher(){
DecimalFormat dec = new DecimalFormat("0.00");
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String userInput = mEditPrice.getText().toString().replaceAll("[^\\d]", "");
int userInputInt = Integer.parseInt(userInput);
mEditPrice.setText("$"+dec.format(userInputInt / 100));
}
在實現所需的功能之前,這里需要解決一些問題。
每當您處理TextWatcher時,在設置要監視的EditText對象的文本時都需要小心。 這樣做的原因是,每次您在其上調用setText時,它將再次觸發監視程序,從而使您的代碼進入無限循環。
為防止這種情況,應將要設置的文本值設置為onTextChanged方法外部的變量。 輸入方法時,請對照此變量進行檢查,僅在該值與CharSequence不同時才執行處理代碼。
整數變量userInputInt除以100時將等於零。
應該將其更改為兩倍以產生0.02等值。
進行這些更改之后,我們可以使EditText輸入2后顯示$ 0.02。但是由於我們已在代碼中設置了EditText的值,因此,EditText的下一個條目將添加到文本的開頭。 然后,如果我們輸入“ 5”,我們將獲得$ 50.02。
為了克服這個問題,我們需要做的最后一件事是使用set position方法將EditText的位置設置為字符串的末尾。
這是最終的解決方案:
private String value;
mEditPrice.addTextChangedListener(new TextWatcher(){
DecimalFormat dec = new DecimalFormat("0.00");
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(value)){
String userInput = mEditPrice.getText().toString().replaceAll("[^\\d]", "");
double userInputDouble = Double.parseDouble(userInput);
value = ("$"+dec.format(userInputDouble / 100));
mEditPrice.setText(value);
mEditPrice.setSelection(value.length());
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.