簡體   English   中英

當EditText失去焦點時,如何避免啟動dialogfragment?

[英]How do I avoid launching dialogfragment when EditText loses focus?

我在EditText行上有一個OnFocusChangeListener,它會啟動一個dialogfragment,以允許用戶從Datepicker中選擇一個日期。 當我在DialogFragment中單擊“設置”時,所選日期將在EditText中設置。 焦點位於EditText行上,光標在設置的日期開始時閃爍。

當我單擊UI屏幕上的另一個EditText行時,DialogFragment再次啟動,這是我不希望的。 基本上,我想在EditText最初獲得焦點時啟動DialogFragment,並在設置日期之后,當用戶移動光標並將焦點移到屏幕上的另一個EditText行時,當EditText失去焦點時,我希望OnFocusChangeListener忽略。 請指教。

這是Activity.java文件中的部分代碼:

    ...
    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");
        }
    });

這是DatePickerFragment.java文件中的部分代碼:

    ...
    // 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);
    }
  }

我相信您忘記了檢查“ editText具有焦點”。 做如下

  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
       }
    }
});

僅當editText獲得焦點時,它才會啟動DialogFragment ,而失去焦點時則什么也不做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM