1

我在 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 不应该是可见的,并且通过以下方式在 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 无法通过键盘获得任何输入。请告诉莫如何摆脱这个错误。

4

1 回答 1

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");
    }
});
于 2012-11-08T10:48:52.067 回答