无法在android中使用setKeyListener

时间:2012-11-08 10:29:57

标签: android android-widget android-edittext

我在EditText中放了一个按钮,我在主XML的启动代码中设置了按钮不可见:

RelativeLayout android:layout_width="match_parent"
    android:layout_height="wrap_content" android:layout_marginTop="10dp">

    <EditText android:id="@+id/editText1" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:hint="@string/search_prompt"/>

    <Button android:id="@+id/button1" android:layout_width="40dp"
        android:layout_height="wrap_content" android:layout_alignBottom="@+id/editText1"
        android:layout_alignParentRight="true" android:layout_alignParentTop="true"
        android:layout_margin="5dp" android:background="@drawable/search"
        android:onClick="loadWeather" android:visibility="invisible"/>

</RelativeLayout>

现在我希望只有在EditText中有一些文本时,如果EditText为空,Button才能显示,Button应该不可见,并且已经按照以下方式在EditText上设置了一个setKeyListener监听器:::

final Button searchButton = (Button) findViewById(R.id.button1);

    final EditText myEditText = (EditText) findViewById(R.id.editText1);
    myEditText.setKeyListener(new KeyListener() {

        public boolean onKeyUp(View arg0, Editable arg1, int arg2, KeyEvent arg3) {
            // TODO Auto-generated method stub
            if(!myEditText.getText().equals("")){
                searchButton.setVisibility(View.VISIBLE);
            }
            return false;
        }

        public boolean onKeyOther(View arg0, Editable arg1, KeyEvent arg2) {
            // TODO Auto-generated method stub
            return false;
        }

        public boolean onKeyDown(View arg0, Editable arg1, int arg2, KeyEvent arg3) {
            // TODO Auto-generated method stub
            return false;
        }

        public int getInputType() {
            // TODO Auto-generated method stub
            return 0;
        }

        public void clearMetaKeyState(View arg0, Editable arg1, int arg2) {
            // TODO Auto-generated method stub

        }
    });

它使Button在启动时不可见,但现在我无法在EditText中输入任何文本,EditText不会通过键盘获得任何输入。请告诉我如何摆脱这个错误。

1 个答案:

答案 0 :(得分:0)

改为使用

myEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count,      int after) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
        if( count == 0){
            searchButton.setVisibility(View.INVISIBLE);
        }  else{
            searchButton.setVisibility(View.VISIBLE); 
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        Log.v(TAG, "afterTextChanged");
    }
});