我是安卓新手。我使用以下指南在 android 中创建了一个日期选择器。http://developer.android.com/guide/topics/ui/controls/pickers.html
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
StringBuilder sb = new StringBuilder();
public static String date;
@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);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);
date = sb.toString();
System.out.println("The date is "+date);
}
我需要将此日期值 (date = sb.toString()) 返回到我的 MainActivity 。由于 onDateSet 方法无效,我该怎么办?
附加信息 - DatePickerDialog 在 MainActivity 类中触发,但不是单键单击。一个按钮旁边有几个过程发生,日期选择器只有在满足特定条件时才会触发。我也不想显示日期值。只是希望它返回以进行进一步处理。
感谢任何形式的指导
更改了 onDataset 方法和 justshow()
public void onDateSet(DatePicker view, int year, int month, int day) {
// 对用户选择的日期做一些事情
sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);
date = sb.toString();
MainActivity.newdate=sb.toString();
System.out.println("The date is "+MainActivity.newdate);
} 公共无效 justShow(){
System.out.println("The date is "+MainActivity.newdate);
}
这是主要的相关部分(在第一次回复中建议进行更改后)
DateToken mydate=new DateToken();
String test=dayvals.get(0);
DialogFragment df=new DatePickerFragment();
if(test.equalsIgnoreCase("day")){
df.show(getSupportFragmentManager(), "DatePik");
}
System.out.println("Date is on Main"+newdate);
DatePickerFragment dpf=new DatePickerFragment();
dpf.justShow();
newdate 是静态 String ,但仍输出 null。在 MainActivity 和 justShow 方法中。但在 onDataSet 方法中日期输出正确