这是我的代码:在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修饰符即可编译代码。

10-04 19:43