Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

android - Date picker dialog shows multiple times

I am creating an android activity which needs to get date from user.My activity has a edit text when it is touched shows the datepicker dialog and shows the date in the edit text.I have completed it by using Datepickerdialog.My problem is when i click the edittext 2 datepickerdialog are shown.

Here is my code...

Activity.class

EditText startDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_event);
    startDate= (EditText) findViewById(R.id.startdate);
    startDate.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            new DatePickerDialogFragment().show(getFragmentManager(),"DatePicker");

            return true;
        }
    });
}

@Override
public void returnDate(String date) {
    startDate.setText(date);
}

DatepickerDialog class

public class DatePickerDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

TheListener listener;

public interface TheListener{
    public void returnDate(String date);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Calendar calendar=Calendar.getInstance();
    int year=calendar.get(Calendar.YEAR);
    int month=calendar.get(Calendar.MONTH);
    int day=calendar.get(Calendar.DAY_OF_MONTH);
    listener = (TheListener) getActivity();


    return new DatePickerDialog(getActivity(),this,year,month,day);
}

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar c=Calendar.getInstance();
    c.set(year,monthOfYear,dayOfMonth);

    SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MM-yyyy");
    String date=dateFormat.format(c.getTime());
    if(listener!=null)
    {
        listener.returnDate(date);
    }

}
}

what is the problem in my code.and how to solve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

write your code like this with ACTION_UP motion event

 @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    new DatePickerDialogFragment().show(getFragmentManager(),"DatePicker");                      
                }
                return false;
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...