|
1. 声明EditText变量,并关联到相应控件上
private EditText sellStartTime;
private EditText sellEndTime;
...
sellStartTime = (EditText)findViewById(R.id.editSellStartTime);
sellEndTime = (EditText)findViewById(R.id.editSellEndTime);
复制代码2. 日期选择器函数
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
String mm;
String dd;
if (monthOfYear <= 9) {
mMonth = monthOfYear + 1;
mm = "0" + mMonth;
}
else {
mMonth = monthOfYear + 1;
mm = String.valueOf(mMonth);
}
if (dayOfMonth <= 9) {
mDay = dayOfMonth;
dd = "0" + mDay;
}
else{
mDay = dayOfMonth;
dd = String.valueOf(mDay);
}
mDay = dayOfMonth;
if (timeFlag == 0) {
sellStartTime.setText(String.valueOf(mYear) + "-" + mm + "-" + dd);
}
else {
sellEndTime.setText(String.valueOf(mYear) + "-" + mm + "-" + dd);
}
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
case 1:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
}
return null;
}
// 隐藏手机键盘
private void hideIM(View edt){
try {
InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
IBinder windowToken = edt.getWindowToken();
if (windowToken != null) {
im.hideSoftInputFromWindow(windowToken, 0);
}
}
catch (Exception e) {
}
}
复制代码3. 注册监听器,当EditText获得焦点时,或者被点击时,打开日期选择器
sellStartTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
timeFlag = 0;
showDialog(0);
}
});
sellEndTime.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
timeFlag = 1;
showDialog(1);
}
});
sellStartTime.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == true) {
timeFlag = 0;
hideIM(v);
showDialog(0);
}
}
});
sellEndTime.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus == true) {
timeFlag = 1;
hideIM(v);
showDialog(1);
}
}
});
复制代码4. 在包含EditText的LinearLayout中,添加语句
android:focusable="true" android:focusableInTouchMode="true"
复制代码这句话是为了防止EditText自动获取焦点,触发日期选择器。 |
|