EditText onClickListener in Android

后端 未结 14 2103
时光取名叫无心
时光取名叫无心 2020-12-02 12:03

I want an EditText which creates a DatePicker when is pressed. So I write the following code:

    mEditInit = (EditText) findViewById(R.id.date_init);
    mE         


        
14条回答
  •  旧巷少年郎
    2020-12-02 12:37

    Normally, you want maximum compatibility with EditText's normal behaviour.

    So you should not use android:focusable="false" as, yes, the view will just not be focusable anymore which looks bad. The background drawable will not show its "pressed" state anymore, for example.

    What you should do instead is the following:

    myEditText.setInputType(InputType.TYPE_NULL);
    myEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // showMyDialog();
        }
    });
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                // showMyDialog();
            }
        }
    });
    

    By setting the input type to TYPE_NULL, you prevent the software keyboard from popping up.

    By setting the OnClickListener and OnFocusChangeListener, you make sure that your dialog will always open when the user clicks into the EditText field, both when it gains focus (first click) and on subsequent clicks.

    Just setting android:inputType="none" or setInputType(InputType.TYPE_NULL) is not always enough. For some devices, you should set android:editable="false" in XML as well, although it is deprecated. If it does not work anymore, it will just be ignored (as all XML attributes that are not supported).

提交回复
热议问题