停止用户多次单击edittext以打开多个对话框

时间:2014-02-22 12:04:35

标签: java android onclick android-edittext android-datepicker

我有一个非常简单的问题。我有EditText,点击后会打开DatePickerDialog。但是,反复单击EditText会打开几个对话框。有没有办法限制用户执行此操作,因此无论点击EditText多少次,都只显示一个对话框?

这是我的XML文件中的EditText

<EditText
    android:id="@+id/etSetDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/spDifficultyLevel"
    android:drawableLeft="@drawable/ic_calendar_view"
    android:ems="10"
    android:focusableInTouchMode="false" 
    android:hint=" Set Date"
/>

以下是代码:

/**
 * Where user selects date, launch datepicker on click
 */

public void selectDate() {
    etSetDate.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            //launch datepicker
            DialogFragment dialogFragment = new StartDatePicker();
            dialogFragment.show(getSupportFragmentManager(),
                "start_date_picker");
        }
    });
}

public class StartDatePicker extends DialogFragment implements
      DatePickerDialog.OnDateSetListener {
    Calendar c = Calendar.getInstance();
    int startYear = c.get(Calendar.YEAR);
    int startMonth = c.get(Calendar.MONTH);
    int startDay = c.get(Calendar.DAY_OF_MONTH);

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the date picker
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this,
            startYear, startMonth, startDay);
        return dialog;
    }
}

2 个答案:

答案 0 :(得分:1)

int flag = 0;
etSetDate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            //launch datepicker

            if(flag == 0)
            {
            DialogFragment dialogFragment = new StartDatePicker();
            dialogFragment.show(getSupportFragmentManager(),
                    "start_date_picker");
             flag = 1;
            }

        }

    });

当你关闭对话框时,再次设置flag = 0

答案 1 :(得分:1)

首先检查片段管理器以查看片段是否存在:

Fragment frag = getSupportFragmentManager().findFragmentByTag("start_date_picker");
if(frag == null) {
    frag = new StartDatePicker();
    frag.show(getSupportFragmentManager(), "start_date_picker");
}

如果frag不为null,则显示对话框。