EditText onClickListener in Android

后端 未结 14 2131
时光取名叫无心
时光取名叫无心 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:23

    The following works perfectly for me.

    First set your date picker widget's input to 'none' to prevent the soft keyboard from popping up:

    
    

    Then add these event listeners to show the dialog containing the date picker:

    // Date picker
    EditText dateEdit = (EditText) findViewById(R.id.date);
    dateOfBirthEdit.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                showDialog(DIALOG_DATE_PICKER);
            }
            return false;
        }
    });
    
    dateEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
    
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                showDialog(DIALOG_DATE_PICKER);
            } else {
                dismissDialog(DIALOG_DATE_PICKER);
            }
        }
    });
    

    One last thing. To make sure typed days, months, or years are correctly copied from the date picker, call datePicker.clearFocus() before retrieving the values, for instance via getMonth().

提交回复
热议问题