我有一个活动,我想要的只是
Activity–> OnClick of Some layout (That has textview)–>Open
Datepicker–> set selected value in txtvalue
我想要使用带有代码的DialogFragment的aceess Datepicker.
package com.app.ourforms.date;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
TextView txt;
public DatePickerFragment() {
}
public DatePickerFragment(TextView txt) {
this.txt = txt;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceSateate) {
Log.i("TAG","Inside onCreateDialog");
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);
return new DatePickerDialog(getActivity(),this,year,month,day);
}
public void onDateSet(DatePicker view,int year,int month,int day) {
Log.i("TAG","Inside onDateSet");
txt.setText(day + "/" + (month + 1) + "/" + year);
// Do something with the date chosen
}
}
上面的代码当Device没有改变它的方向时工作正常.但是当显示Datepicker并且方向更改时,我将强制关闭,如下所示
01-04 07:34:14.580: E/AndroidRuntime(2375): FATAL EXCEPTION: main
01-04 07:34:14.580: E/AndroidRuntime(2375): java.lang.NullPointerException
01-04 07:34:14.580: E/AndroidRuntime(2375): at com.app.ourforms.date.DatePickerFragment.onDateSet(DatePickerFragment.java:39)
01-04 07:34:14.580: E/AndroidRuntime(2375): at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:148)
01-04 07:34:14.580: E/AndroidRuntime(2375): at android.app.DatePickerDialog.onClick(DatePickerDialog.java:116)
01-04 07:34:14.580: E/AndroidRuntime(2375): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
01-04 07:34:14.580: E/AndroidRuntime(2375): at android.os.Handler.dispatchMessage(Handler.java:99)
01-04 07:34:14.580: E/AndroidRuntime(2375): at android.os.Looper.loop(Looper.java:137)
01-04 07:34:14.580: E/AndroidRuntime(2375): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-04 07:34:14.580: E/AndroidRuntime(2375): at java.lang.reflect.Method.invokeNative(Native Method)
01-04 07:34:14.580: E/AndroidRuntime(2375): at java.lang.reflect.Method.invoke(Method.java:511)
01-04 07:34:14.580: E/AndroidRuntime(2375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-04 07:34:14.580: E/AndroidRuntime(2375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-04 07:34:14.580: E/AndroidRuntime(2375): at dalvik.system.NativeStart.main(Native Method)
public void showDatePickerDialog(View v) {
Log.i("TAG","Inside showDatePickerDialog");
DialogFragment newFragment = new DatePickerFragment((TextView)v);
newFragment.show(getFragmentManager(),"datePicker");
}
请帮我摆脱这个.
提前致谢.
最佳答案
原文链接:https://www.f2er.com/android/430761.html