我在 同一活动
中有 两个 日期选择器当用户点击设备上的后退按钮时,系统会想知道用户更改了哪个日期选择器日期
并注意:
两个日期选择器已连接,当用户更换一个选择器时 日期另一个选择日期也会以特定方式更改,具体取决于 第一个选择器
有没有办法这样做?
答案 0 :(得分:2)
我没有对此进行过测试,但我认为这应该可行:
private DatePicker datePicker1;
private DatePicker datePicker2;
//...
OnDateChangedListener listener = new OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
if (datePicker1.equals(view)) {
// Date of datePicker1 is changed
// ...
}
else if (datePicker2.equals(view)) {
// Date of datePicker2 is changed
// ...
}
}
datePicker1.init(2012, 11, 27, listener);
datePicker2.init(2012, 11, 27, listener);
答案 1 :(得分:1)
您需要做的是获取对EditText和DatePicker的引用:
EditText editText = (EditText) findViewById( R.id.dateSelectionEditText );
DatePicker datePicker = (DatePicker) findViewById( R.id.datePicker );
Then you need to create an OnDateChangedListener:
private class MyOnDateChangedListener implements OnDateChangedListener {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
editText.setText( "" + dayOfMonth + "-" + (monthOfYear + 1) + "-" + year );
}
};
剩下的就是初始化DatePicker:
datePicker.init( year, monthOfYear, dayOfMonth, new MyOnDateChangedListener() ).
http://developer.android.com/guide/topics/ui/controls/pickers.html
在您的活动中全局初始化这些变量,
private EditText zopenDate;
Button calendar;
private int mYear;
private int mMonth;
private int mDay;
private DatePickerDialog.OnDateSetListener mDateSetListener;
在您的实例中
calendar=(Button)findViewById(R.id.datePicker);
zopenDate=(EditText)findViewById(R.id.dateSelectionEditText);
inside your instance use this listeners,
mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
calendar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// display the current date (this method is below)
updateDisplay();
the funtion updatedisplay() outside createInstance(),
private void updateDisplay() {
zopenDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}