Bug or error in DialogPicker

2019-08-30 05:05发布

问题:

i have a edittext, when edittext is clicked, it will show a DialogPicker.

My object:

static final int DATE_DIALOG_ID = 1;
private EditText txtDate;
private EditText tambah;

here my code:

txtDate = (EditText) rootView.findViewById(R.id.tanggal);
txtDate.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            DialogFragment newFragment = new DialogFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            //newFragment.setTxtDate(txtDate);
            newFragment.show(ft, "dialog");
            return true;

        }
    });

public static class SomeDialog extends DialogFragment {
    final Calendar c = Calendar.getInstance();
    private String[] arrMonth = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);
    EditText txtDate;
    DatePickerDialog a;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (a == null) {
            a = new DatePickerDialog(
                    getActivity(), mDateSetListener, mYear, mMonth, mDay);
        }
      return a;
  }
    public void setTxtDate(EditText a){
        txtDate = a;
    }
    public DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener()
            { 
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                String sdate = arrMonth[mMonth] + " " + LPad(mDay + "", "0", 2) + ", " + mYear;
                SomeDialog.this.txtDate.setText(sdate);                    
            }
            protected String LPad(String schar, String spad, int len) {
                String sret = schar;
                for (int i = sret.length(); i < len; i++) {
                    sret = spad + sret;
                }
                return new String(sret);
            }
        };
}   

when i click the edittext, the datepicker will show morethan once. how i fix it?, just info, i using a fragment in this code. thanks for your answer.

回答1:

Its not the Bug. onTouchListenr calls many times ontouch of EditText. like when MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP. so you need to change your code like

public boolean onTouch(View arg0, MotionEvent arg1) {
    if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
        DialogFragment newFragment = new DialogFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        // newFragment.setTxtDate(txtDate);
        newFragment.show(ft, "dialog");
    }
    return true;
}