gpt4 book ai didi

java - 无法解析 DateSetListener 对象

转载 作者:行者123 更新时间:2023-11-30 11:27:33 25 4
gpt4 key购买 nike

这是我的代码:在 onClick() 方法中声明的 datepickobj 似乎无法识别在 DatePickerDialog.OnDateSetListener 中创建的对象。我收到“datepickobj 无法解析为变量”错误!非常感谢任何帮助。

protected void onCreate(Bundle savedInstanceState) {  
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userdate =(EditText) findViewById(R.id.user_datespent);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date da = new Date();
userdate.setText( sdf.format(da));
final Calendar cal = Calendar.getInstance();



Button changeDate = (Button) findViewById(R.id.button_for_cal);
changeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatePickerDialog(this, datepickobj, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
userdate.setText("");
}
});

DatePickerDialog.OnDateSetListener datepickobj = new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cday = dayOfMonth;
cmonth = monthOfYear + 1;
cyear = year;

userdate.setText("Choosen date is :" + cday + "/" + cmonth + "/" + cyear);
}
};

最佳答案

移动 datepickobj 使其位于该行之前

changeDate.setOnClickListener(new OnClickListener() {  

并将其声明为final

protected void onCreate(Bundle savedInstanceState) {  
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userdate =(EditText) findViewById(R.id.user_datespent);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date da = new Date();
userdate.setText( sdf.format(da));
final Calendar cal = Calendar.getInstance();

final DatePickerDialog.OnDateSetListener datepickobj = new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cday = dayOfMonth;
cmonth = monthOfYear + 1;
cyear = year;

userdate.setText("Choosen date is :" + cday + "/" + cmonth + "/" + cyear);
}
};

Button changeDate = (Button) findViewById(R.id.button_for_cal);
changeDate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatePickerDialog(this, datepickobj, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
userdate.setText("");
}
});
}

Java 中的方法范围变量在声明方面遵循线性模式,您不能在方法末尾声明变量并尝试在之前的任何地方使用它。

使用 final 修饰符是因为您在匿名内部类中使用 datepickobj。如果您将 datepickobj 设置为实例变量(也就是说,在任何方法之外,在类的根部),则不需要 final 修饰符来获取代码编译。

关于java - 无法解析 DateSetListener 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com