gpt4 book ai didi

java - 如何在 Android 中监听 TextView 并对同一个 TextView 进行更改

转载 作者:行者123 更新时间:2023-12-01 12:24:02 25 4
gpt4 key购买 nike

我尝试了以下代码,但是 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种可能的解决方案:

  1. 检查字符串中是否存在回车符

像这样:

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");
}
}
});

根据输入字符串中的内容,这不是最佳解决方案

  • 在 beforeTextChanged 中执行
  • 像这样:

    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);

    关于java - 如何在 Android 中监听 TextView 并对同一个 TextView 进行更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26484540/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com