通过EditText上的addTextChangedListener添加TextWatcher无效

时间:2014-01-17 17:09:37

标签: android android-edittext

我正在尝试将TextWatcher附加到EditText。这是在onCreate()中完成的。我知道EditText已成功找到。但是,当活动启动时,在EditText中进行更改时没有任何反应。我已经尝试在TextWatcher中的三个重写函数中编辑代码来执行除调用函数之外的操作,但这也没有效果

相关代码:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }

    setContentView(R.layout.fragment_main);
    EditText myEditText = (EditText) findViewById(R.id.cost);
    myEditText.addTextChangedListener(new TextWatcher(){

        @Override
        public void afterTextChanged(Editable s) {
            updatePrice(null);
        }

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count){
            updatePrice(null);
        }
    });
    setContentView(R.layout.activity_main);
}

从布局:

<EditText
    android:id="@+id/cost"
     ... 
    android:inputType="numberDecimal" />

堆栈追踪:

java.lang.RuntimeException: Unable to start activity         ComponentInfo{com.example.paymeback/com.example.paymeback.MainActivity}:     java.lang.IllegalArgumentException: No view found for id 0x7f07003c     (com.example.paymeback:id/container) for fragment PlaceholderFragment{b1d7ce60 #0     id=0x7f07003c}
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f07003c (com.example.paymeback:id/container) for fragment PlaceholderFragment{b1d7ce60 #0 id=0x7f07003c}
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)

1 个答案:

答案 0 :(得分:2)

您正在呼叫setContentView三次。为什么?你应该只调用一次。当您在上一次调用EditText时更换活动的内容视图时,您TextWatcher添加setContentView的内容正在被处置,所以无论您EditText是什么在您的活动启动时输入,与您添加观察者的内容不同。