我有两个ImageButtons。一个负责设置开始日期,另一个负责设置结束日期。按下每个按钮时,它们会显示一个DatePickerDialog。 onCreateDialog方法在另一个类中。这是班级:
DatePickerFragment.Java
package com.ThatOneNoob.smarthaul;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker v, int year, int month, int day) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.datesel1:
toDate.setText(new StringBuffer());
}
}
}
显然不完整,toDate是它想要管理的TextView之一。 datesel1是ImageButton。它将附加TextView以包含01/02/2013格式的设置日期。我不能将TextView声明为静态,因此我无法在此类中调用它。那么,我应该让onDateSet调用一个静态方法来将TextView设置为它需要做什么吗?或者我该怎么办?
答案 0 :(得分:5)
在单独的类中创建对话框并为侦听器创建一个getter:
public class DatePickerFragment extends DialogFragment
{
private OnDateSetListener onDateSetListener;
public DatePickerFragment() {}
public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
this.onDateSetListener = onDateSetListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), onDateSetListener, year, month, day);
}
}
DatePickerDialog.OnDateSetListener的实现在您引用TextView的其他片段的活动中生成。
然后创建一个日历并使用SimpleDateFormat,查看example:
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar cal = Calendar.getInstance();
cal.set(year, monthOfYear, dayOfMonth);
<=== YOUR SETTEXT TO YOUR TEXTVIEW HERE ===>
}