我有一个编辑文本框,并且我调用了ontouchlistener,它显示了一个自定义对话框,当我单击setdate按钮时,应该在编辑文本上设置日期选择器上的日期,并且该对话框应该关闭.但我不知道如何从日期选择器中获取日期以及如何在编辑文本框中进行设置.我在date.init(year,monthOfYear,dayOfMonth,new MyOnDateChangedListener())中遇到错误;并且错误是这一行的多个标记
-dayOfMonth无法解析为
变量
-无法将年份解析为变量
-无法将monthOfYear解析为
变量
et4.setOnTouchListener(new OnTouchListener() {
final Dialog setdatedialog = new Dialog(DropboxActivity.this);
public void onClick(View v) {
}
public boolean onTouch(View arg0, MotionEvent arg1) {
setdatedialog.setContentView(R.layout.datedialog);
setdatedialog.setTitle("select date of puchase");
setdatedialog.setCancelable(true);
setdatedialog.show();
Button back = (Button)setdatedialog.findViewById(R.id.back3);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setdatedialog.dismiss();
}
});
Button setdate=(Button)setdatedialog.findViewById(R.id.setdate);
DatePicker date = (DatePicker)setdatedialog.findViewById(R.id.datePicker1);
class MyOnDateChangedListener implements OnDateChangedListener {
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){
et4.setText( "" + dayOfMonth + "-" + (monthOfYear + 1) + "-" + year );
}
};
date.init( year, monthOfYear, dayOfMonth, new MyOnDateChangedListener() );
return false;
}
解决方法:
在xml中定义editText和Button,并在您的活动中定义以下代码:
editText=(EditText) findViewById(R.id.date);
button=(Button) findViewById(R.id.play);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
Calendar c=Calendar.getInstance();
mYear=c.get(Calendar.YEAR);
mMonth=c.get(Calendar.MONTH);
mDay=c.get(Calendar.DAY_OF_MONTH);
现在添加这两个函数以调用DatePicker对话框并在Edittext中设置日期
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() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
editText.setText(new StringBuilder().append(mDay).append("/").append(mMonth+1).append("/").append(mYear));
}
};
全局定义:
static final int DATE_DIALOG_ID = 0;
private int mYear,mMonth,mDay;
这将帮助您在editText中设置日期.希望对您有帮助.