[英]How can I listen on TextView and make changes to the same TextView in android
我尝试了以下代码,但是android不允许我这样做,因为我进入了无限循环。
mEditText = (EditText) getActivity().findViewById(R.id.input_content);
mEditText.addTextChangedListener(new TextWatcher(){
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void afterTextChanged(Editable s) {
//I want to format the already existing text in s in a certain way as the user is typing
mEditText.setText(s.toString() + " \n");
}
});
请任何想法将非常有帮助。 谢谢
3种可能的解决方案:
像这样 :
mEditText = (EditText) getActivity().findViewById(R.id.input_content);
mEditText.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s)
{
//I want to format the already existing text in s in a certain way as the user is typing
if (s.toString().charAt(s.length() - 1 ) != '\n')
{
mEditText.setText(s.toString() + " \n");
}
}
});
根据您输入字符串中的内容,这不是最佳解决方案
像这样 :
mEditText = (EditText) getActivity().findViewById(R.id.input_content);
mEditText.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
//I want to format the already existing text in s in a certain way as the user is typing
mEditText.setText(s.toString() + " \n");
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {}
});
像这样 :
final TextWatcher tw = new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s)
{
//I want to format the already existing text in s in a certain way as the user is typing
mEditText.removeTextChangedListener(tw);
mEditText.setText(s.toString() + " \n");
mEditText.addTextChangedListener(tw);
}
});
mEditText = (EditText) getActivity().findViewById(R.id.input_content);
mEditText.addTextChangedListener(tw);
您最有可能进入无限循环,因为您是在public void afterTextChanged(Editable s)
中更改文本,这将导致再次调用该方法。
最好的解决方案是使用其他方法之一更改文本,或者在失去可编辑焦点的情况下。 有关更多详细信息,请参见View.OnFocusChangeListener 。
这是一个例子:
textView.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
textView.setText(s.toString() + " \n");
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.