如何在Android中创建2个DateTimePicker

时间:2014-03-22 03:07:27

标签: android datetime datetimepicker

现在我想问一下,我试图创建2个datetimepicker并尝试在android中的两个不同的editText(文本框)中获取值,这里是我的代码,我在下面的代码中签署注释

public class CreateData extends Activity implements OnClickListener{
    int hour, minute, mYear,mMonth, mDay;
    static final int DATE_DIALOG_ID = 1;

    private String[] arrMonth = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
 private EditText txtDate;
 private EditText txtDate2;

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.create_data);

    txtDate         = (EditText) findViewById(R.id.Date1);
    txtDate2        = (EditText) findViewById(R.id.Date2);

    final Calendar c = Calendar.getInstance();
    mYear   = c.get(Calendar.YEAR);
    mMonth  = c.get(Calendar.MONTH);
    mDay    = c.get(Calendar.DAY_OF_MONTH);

    txtDate.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
             showDateDialog(txtDate, Calendar.getInstance());
            return true;

        }
    });

    txtDate2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
             showDateDialog(edTgl_akreditasi, Calendar.getInstance());
            return true;

        }
    }); 
  }

  EditText activeDateDisplay;
  Calendar activeDate;


   public void showDateDialog(EditText dateDisplay, Calendar date) 
    {
       activeDateDisplay = dateDisplay;
       activeDate = date;
       showDialog(DATE_DIALOG_ID);
    }
   @Override
   protected Dialog onCreateDialog(int id)
   {
      switch (id) 
       {
            case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
       }
    return null;
  }

 private 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;
            txtDate.setText(sdate); //until here txtDate can get a value from the datetime picker, but how to set txtDate2 to get value from different datetimepicker?

        }
};

我真的需要帮助。谢谢你

1 个答案:

答案 0 :(得分:0)

只需将txtDate.setText(sdate);更改为activeDateDisplay.setText(sdate);即可。同样在editdate2的ontouchlistener中,我不知道dTgl akreditasi是什么,但我认为它应该是showDateDialog(editdate2, Calendar.getInstance());而不是showDateDialog(edTgl_akreditasi, Calendar.getInstance());