简体   繁体   中英

How do I avoid launching dialogfragment when EditText loses focus?

I have a OnFocusChangeListener on an EditText line that launches a dialogfragment to allow the user to select a date from a Datepicker. When I click "Set" on the DialogFragment, the selected date is set in the EditText. Focus is on the EditText line with the cursor blinking at the beginning of the date that was set.

As soon as I click to another EditText line on the UI screen, the DialogFragment launches again, which I don't want. Basically I want to launch the DialogFragment when the EditText initially gains focus and after setting the date, I want the OnFocusChangeListener to ignore when the EditText loses focus as the user moves the cursor and focus to another EditText line on the screen. Please advise.

Here is partial code in Activity.java file:

    ...
    fListenerEditText = (ListenerEditText) findViewById(R.id.FEditText);

    fListenerEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
        }
    });

Here is partial code in DatePickerFragment.java file:

    ...
    // Puts the selected date into the EditText line.
    public void onDateSet(DatePicker view, int year, int month, int day) {
    txtDate = (EditText) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.FEditText);
    String date=(month+1) + "/" + day + "/" + year;
    txtDate.setText(date);
    }

    // When the dialog date is set the dialogfragment closes and the softkeboard re-loads back on the CardViewActivity.
    public void onDismiss(final DialogInterface dialog) {
    super.onDismiss(dialog);
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
    // The soft keyboard always closes when the DialogFragment is displayed.  So the
    // line below toggles the soft keyboard to show again.
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }
  }

I believe you have forgot to put a check of "if editText having focus or not". Do as following

  fListenerEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
      if(hasFocus){
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
       }
      else {
         // do nothing
       }
    }
});

It will launch your DialogFragment only when editText gains focus and will do nothing focus lose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM