如何在addTextChangedListener中访问视图?

时间:2018-12-11 04:16:31

标签: android android-studio addtextchangedlistener

我想添加一种方法,其中将视图作为参数传递是直接添加某种方法(视图)显示错误的代码。

abc.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) {
   somemethod(view); // this is where I stuck
  }
 }
}

@Override
public void afterTextChanged(Editable s) {

}
});
.....
somemethod(View view) {}

2 个答案:

答案 0 :(得分:1)

private class MyTextWatcher implements TextWatcher {

    private View view;

    private MyTextWatcher(View view) {
        this.view = view;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //access view
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //access view
    }

    @Override
    public void afterTextChanged(Editable s) {
        //access view
    }
}

将侦听器添加到视图

editText.addTextChangedListener(new MyTextWatcher(editText));

答案 1 :(得分:0)

我想你的问题有点模糊。如果从OnCreate()运行此代码,则可以按以下方式获取视图,否则,如果从其他onclick方法获取视图,则该视图将作为参数使用。

final View view = findViewById(android.R.id.content);