-1

我有一个活动,它的一个功能逻辑是在另一个类中计算的,在这里我计算在编辑文本字段中输入内容时,我使用文本观察器。

主要活动代码:

public class UnitConverter extends AppCompatActivity {
    public EditText input;
    .
    ......
    input = (EditText) findViewById(R.id.etInput);
    .........
    case Sample :
         new AnotherClass();
}

input我在这个领域使用 textwatcher ,

另一个类代码:

public class AnotherClass {
UnitConverter ac = new UnitConverter();
public AnotherClass() {
    ac.input.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) {
     }
  }
}

收到空指针错误,

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.addTextChangedListener(android.text.TextWatcher)' on a null object reference                                                                       
4

1 回答 1

1

您需要将活动引用传递给另一个类,如下所示:

主要活动代码:

public class UnitConverter extends AppCompatActivity {
    public EditText input;
    .
    ......
    input = (EditText) findViewById(R.id.etInput);
    .........
    case Sample :
        new AnotherClass(UnitConverter.this);
}

另一个类代码:

public class AnotherClass {
    public AnotherClass(UniteConverter ac) {
    ac.input.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) {
      }
  }
}
于 2016-06-01T10:33:00.900 回答