只要改变EditText
字符串,就调用onTextChanged
。
现在,当我启动一个新的Activity
并通过Bundle
发送数据时,onTextChanged
没有被调用。
if( getIntent().getExtras() != null) {
Bundle b = getIntent().getExtras();
int value = -1;
if(b != null)
value = b.getInt("key");
edit1.setText("Mywords:");
}
如何命名?
这是修改后的代码。这个想法是在添加TextWatcher
之后在EditText
中设置文本。
if( getIntent().getExtras() != null) {
Bundle b = getIntent().getExtras();
int value = -1;
if(b != null)
value = b.getInt("key");
// Add the TextWatcher here
edit1.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Toast.makeText(MainActivity.this, "before text changed", Toast.LENGTH_LONG).show();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Toast.makeText(MainActivity.this, "on text changed", Toast.LENGTH_LONG).show();
}
@Override
public void afterTextChanged(Editable s) {
// Toast.makeText(MainActivity.this, "after text changed", Toast.LENGTH_LONG).show();
}
});
// Now the set the value in your EditText
edit1.setText("Mywords:");
}
确保在setText
调用之前订阅TextWatcher
由于某种原因,方法addTextChangedListener
没有为我调用。
然而doBeforeTextChanged
, doOnTextChanged
和doAfterTextChanged
的方法效果很好:
amountTextField.doBeforeTextChanged { text, start, count, after ->
Log.d(TAG, "beforeTextChange.") // OK, called
}
amountTextField.doOnTextChanged { text, start, before, count ->
Log.d(TAG, "onTextChanged.") // OK, called
}
amountTextField.doAfterTextChanged {
Log.d(TAG, "afterTextChanged.") // OK, called
}
amountTextField.addTextChangedListener {
object: TextWatcher {
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
Log.d(TAG, "beforeTextChange.") // NOK, not called
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
Log.d(TAG, "onTextChanged.") // NOK, not called
}
override fun afterTextChanged(p0: Editable?) {
Log.d(TAG, "onTextChanged.") // NOK, not called
}
} }
顺便说一下,结果总是一样的:无论我是否将任何文本设置为我的EidtText,无论是在我设置任何文本之后还是之前。
尝试如下:
edit1.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) {
}
});
参考:android on Text Change Listener