如何检测字符是否输入到EditText中,使其长度为0到1个字符然后执行某些操作?
既然你有一个相当抽象的问题,让我尝试一个同样通用的答案:
在你的onCreate()
中,声明并施放你的EditText
EditText editText = (EditText) findViewById(R.id.editText);
editText.addTextChangedListener(filterTextWatcher);
然后,在onCreate()
之外,像这样设置filterTextWatcher
:
private TextWatcher filterTextWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// DO THE CALCULATIONS HERE AND SHOW THE RESULT AS PER YOUR CALCULATIONS
int radius = 0;
radius = Integer.valueof(s.toString);
double area = Math.PI * radius * radius;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
编辑:
更新了可能的计算代码。 (未经测试的代码:我只是在没有测试的情况下将其打字。修改是必要的)
了解更多关于TextWatcher's here的信息
以下是一些让您入门的示例:
您可以在EditText上使用TextWatcher并处理您想要对用户执行的操作立即输入数据。
这是用户输入数据时立即格式化的示例
final EditText EditTxtFinancialCode = (EditText) findViewById(R.id.edtNewCpFinancialCode);
EditTxtFinancialCode.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String a = "";
boolean flag = true;
String eachBlock[] = EditTxtFinancialCode.getText().toString().split("-");
for (int i = 0; i < eachBlock.length; i++) {
if (eachBlock[i].length() > 4) {
flag = false;
}
}
if (flag) {
EditTxtFinancialCode.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
KeyDel = 1;
return false;
}
});
if (KeyDel == 0) {
if (((EditTxtFinancialCode.getText().length() + 1) % 5) == 0) {
if (EditTxtFinancialCode.getText().toString().split("-").length <= 2) {
EditTxtFinancialCode.setText(EditTxtFinancialCode.getText() + "-");
EditTxtFinancialCode.setSelection(EditTxtFinancialCode.getText().length());
}
}
a = EditTxtFinancialCode.getText().toString();
} else {
a = EditTxtFinancialCode.getText().toString();
KeyDel = 0;
}
} else {
EditTxtFinancialCode.setText(a);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
http://developer.android.com/reference/android/widget/TextView.OnEditorActionListener.html
做一个听众。
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);
myOutputBox.setText(s);
}
});
见http://www.mysamplecode.com/2012/06/android-edittext-text-change-listener.html