2

我似乎无法设置我的 DateTimeDialogFragment 因为它一直在我放置的部分崩溃:

datePicker = (DatePicker) getView().findViewById(R.id.DatePicker);

错误日志:

02-14 21:38:43.262: E/AndroidRuntime(2435): FATAL EXCEPTION: main
02-14 21:38:43.262: E/AndroidRuntime(2435): java.lang.NullPointerException
02-14 21:38:43.262: E/AndroidRuntime(2435):     at com.test.DateTimeDialogFragment.onActivityCreated(DateTimeDialogFragment.java:98)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:847)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.BackStackRecord.run(BackStackRecord.java:622)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.os.Handler.handleCallback(Handler.java:605)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.os.Looper.loop(Looper.java:137)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at android.app.ActivityThread.main(ActivityThread.java:4424)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at java.lang.reflect.Method.invokeNative(Native Method)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at java.lang.reflect.Method.invoke(Method.java:511)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-14 21:38:43.262: E/AndroidRuntime(2435):     at dalvik.system.NativeStart.main(Native Method)

这是完整的代码:

public class DateTimeDialogFragment extends DialogFragment implements
        OnDateChangedListener, OnTimeChangedListener {
    // Define constants for date-time picker.
    public final int DATE_PICKER = 1;
    public final int TIME_PICKER = 2;
    public final int DATE_TIME_PICKER = 3;

    // DatePicker reference
    private DatePicker datePicker;

    // TimePicker reference
    private TimePicker timePicker;

    // Calendar reference
    private Calendar mCalendar;

    // Define activity
    private Activity activity;

    // Define Dialog type
    private int intDialogType;

    // Constructor start
    public DateTimeDialogFragment(Activity activity) {
        this.activity = activity;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        // Get the layout inflater
        LayoutInflater inflater = activity.getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.date_time_dialog, null));

        // Set title of dialog
        builder.setMessage("Set Date")
                // Set Ok button
                .setPositiveButton("Set",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User ok the dialog
                            }
                        })
                // Set Cancel button
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                            }
                        })
                // Set Neutral button (reset Time / Date)
                .setNeutralButton("Reset",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                // User reset the dialog
                                // reset();
                            }
                        });

        // Create the AlertDialog object and return it
        return builder.create();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        // Grab a Calendar instance
        mCalendar = Calendar.getInstance();

        // Init date picker
        datePicker = (DatePicker) getView().findViewById(R.id.DatePicker);
        datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

        // Init time picker
        timePicker = (TimePicker) getView().findViewById(R.id.TimePicker);
        timePicker.setOnTimeChangedListener(this);
    }

    public void setIntDialogType(int intDialogType) {
        this.intDialogType = intDialogType;
    }

    // Convenience wrapper for internal Calendar instance
    public int get(final int field) {
        return mCalendar.get(field);
    }

    // Reset DatePicker, TimePicker and internal Calendar instance
    public void reset() {
        final Calendar c = Calendar.getInstance();
        updateDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
    }

    // Convenience wrapper for internal Calendar instance
    public long getDateTimeMillis() {
        return mCalendar.getTimeInMillis();
    }

    // Convenience wrapper for internal TimePicker instance
    public void setIs24HourView(boolean is24HourView) {
        timePicker.setIs24HourView(is24HourView);
    }

    // Convenience wrapper for internal TimePicker instance
    public boolean is24HourView() {
        return timePicker.is24HourView();
    }

    // Convenience wrapper for internal DatePicker instance
    public void setCalendarViewShown(boolean calendarView) {
        datePicker.setCalendarViewShown(calendarView);
    }

    // Convenience wrapper for internal DatePicker instance
    public boolean CalendarViewShown() {
        return datePicker.getCalendarViewShown();
    }

    // Convenience wrapper for internal DatePicker instance
    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
        datePicker.updateDate(year, monthOfYear, dayOfMonth);
    }

    // Convenience wrapper for internal TimePicker instance
    public void updateTime(int currentHour, int currentMinute) {
        timePicker.setCurrentHour(currentHour);
        timePicker.setCurrentMinute(currentMinute);
    }

    public String getDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        return sdf.format(mCalendar.getTime());
    }

    // Called every time the user changes DatePicker values
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // Update the internal Calendar instance
        mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
    }

    // Called every time the user changes TimePicker values
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        // Update the internal Calendar instance
        mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
    }

这是 date_time_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DateTimePicker"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="5dip" >

    <DatePicker
        android:id="@+id/DatePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginRight="40dp" />

    <TimePicker
        android:id="@+id/TimePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>
4

3 回答 3

5

我要感谢大家帮助我并带领我朝着正确的方向前进。我现在对Android有了更好的了解。这是完整的工人阶级:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class DateTimeDialogFragment extends DialogFragment implements OnDateChangedListener, OnTimeChangedListener {
    // Define constants for date-time picker.
    public final static int DATE_PICKER = 1;
    public final static int TIME_PICKER = 2;
    public final static int DATE_TIME_PICKER = 3;

    // DatePicker reference
    private DatePicker datePicker;

    // TimePicker reference
    private TimePicker timePicker;

    // Calendar reference
    private Calendar mCalendar;

    // Define activity
    private Activity activity;

    // Define Dialog type
    private int DialogType;

    // Define Dialog view
    private View mView;

    // Constructor start
    public DateTimeDialogFragment(Activity activity) {
        this(activity, DATE_TIME_PICKER);
    }

    public DateTimeDialogFragment(Activity activity, int DialogType) {
        this.activity = activity;
        this.DialogType = DialogType;

        // Inflate layout for the view
        // Pass null as the parent view because its going in the dialog layout
        LayoutInflater inflater = activity.getLayoutInflater();
        mView = inflater.inflate(R.layout.date_time_dialog, null);  

        // Grab a Calendar instance
        mCalendar = Calendar.getInstance();

        // Init date picker
        datePicker = (DatePicker) mView.findViewById(R.id.DatePicker);
        datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

        // Init time picker
        timePicker = (TimePicker) mView.findViewById(R.id.TimePicker);

        // Set default Calendar and Time Style
        setIs24HourView(true);
        setCalendarViewShown(false);

        switch (DialogType) {
        case DATE_PICKER:
            timePicker.setVisibility(View.GONE);
            break;
        case TIME_PICKER:
            datePicker.setVisibility(View.GONE);
            break;
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        Builder builder = new AlertDialog.Builder(activity);

        // Set the layout for the dialog
        builder.setView(mView);

        // Set title of dialog
        builder.setMessage("Set Date")
                // Set Ok button
                .setPositiveButton("Set",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User ok the dialog
                            }
                        })
                // Set Cancel button
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // User cancelled the dialog
                                DateTimeDialogFragment.this.getDialog().cancel();
                            }
                        }); 

        // Create the AlertDialog object and return it
        return builder.create();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        timePicker.setOnTimeChangedListener(this);
    }

    // Convenience wrapper for internal Calendar instance
    public int get(final int field) {
        return mCalendar.get(field);
    }

    // Convenience wrapper for internal Calendar instance
    public long getDateTimeMillis() {
        return mCalendar.getTimeInMillis();
    }

    // Convenience wrapper for internal TimePicker instance
    public void setIs24HourView(boolean is24HourView) {
        timePicker.setIs24HourView(is24HourView);
    }

    // Convenience wrapper for internal TimePicker instance
    public boolean is24HourView() {
        return timePicker.is24HourView();
    }

    // Convenience wrapper for internal DatePicker instance
    public void setCalendarViewShown(boolean calendarView) {
        datePicker.setCalendarViewShown(calendarView);
    }

    // Convenience wrapper for internal DatePicker instance
    public boolean CalendarViewShown() {
        return datePicker.getCalendarViewShown();
    }

    // Convenience wrapper for internal DatePicker instance
    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
        datePicker.updateDate(year, monthOfYear, dayOfMonth);
    }

    // Convenience wrapper for internal TimePicker instance
    public void updateTime(int currentHour, int currentMinute) {
        timePicker.setCurrentHour(currentHour);
        timePicker.setCurrentMinute(currentMinute);
    }

    public String getDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        return sdf.format(mCalendar.getTime());
    }

    // Called every time the user changes DatePicker values
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // Update the internal Calendar instance
        mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
    }

    // Called every time the user changes TimePicker values
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        // Update the internal Calendar instance
        mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
    }
}
于 2013-02-15T05:39:55.437 回答
3

编辑:

嗨,我使用过您的相同代码,并且可以打开日期和时间选择器对话框...您错过的地方是您没有夸大布局以获得视图

尝试像这样更改您的 onActivityCreate

public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// Grab a Calendar instance
mCalendar = Calendar.getInstance();
LayoutInflater inflater = activity.getLayoutInflater();

//Inflate and set the layout for the dialog
//Pass null as the parent view because its going in the dialog layout
View v=inflater.inflate(R.layout.date_time_dialog, null);

// Init date picker
datePicker = (DatePicker)v.findViewById(R.id.DatePicker);
datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);

// Init time picker
timePicker = (TimePicker) v.findViewById(R.id.TimePicker);
timePicker.setOnTimeChangedListener(this);
}

这将解决您的问题....我很自信,因为使用相同的代码我已经成功打开了对话框。


嗨,请参阅有关OnActivityCreate的文档

根据文档, 这在 onCreateView(LayoutInflater, ViewGroup, Bundle) 之后和 onViewStateRestored(Bundle) 之前调用。你需要使用 onCreateView 来获取 datePicker = (DatePicker) getView().findViewById(R.id.DatePicker); 这个...我不确定,但我已经用这样的对话框实现了 DatePicker,它可能会有所帮助

public class DateDialogFragment extends DialogFragment implements
            OnDateSetListener {
        boolean fired = false;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {

            if (fired == true) {
                return;
            } else {
                // first time fired
                fired = true;
            }
            String date = checkDigit(monthOfYear + 1) + "/"
                    + checkDigit(dayOfMonth) + "/" + year;
            strDate = date;
            getAppointments(date);
        }
    }

格式化结果日期

   public String checkDigit(int number) {
            return number <= 9 ? "0" + number : String.valueOf(number);
        }

并在你的Activity中这样使用(推荐使用FragmentActivity)

 DateDialogFragment datepicker = new DateDialogFragment();
                datepicker.show(getSupportFragmentManager(), "DatePicker");
于 2013-02-15T05:46:38.467 回答
1

你可以试试这个不使用 AlertDialog.Builder的实现,你可以参考view. 以便您可以调用view.findViewById(R.id.yourViewItem).

编辑: Pragnani 的解决方案和建议也帮助了我。非常感谢。

于 2013-02-15T05:18:30.503 回答