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);
        }

アクティビティでこのように使用します(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 に答える