日期时间选择器 android

DateTimePicker android

我正在制作一个 DateTime Picker,以便在我在 datePicker 片段上选择一个日期并从选取器中获取一个 Calendar 对象后立即获得 timePicker 片段。

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

    public void onDateSet(DatePicker view, int year, int month, int day) {

    }

}

TimePicker 片段

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        final Calendar c=Calendar.getInstance();
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minute=c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

    }
}

如何连接这些片段以依次显示以及如何在从两个片段获取数据后获取单个日历对象?

    public class myDateObject {
        int year;
        int month;
        int day;

        public myDateObject(int year, int month, int day) {
            this.year = year;
            this.month = month;
            this.day = day;
        }
    }   

        public class MainActivity extends AppCompatActivity{
            MyDateObject myDate;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                yourButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                       if(myDate!=null){
                       FragmentTransaction ft =          
                       getSupportFragmentManager().beginTransaction();
                       Fragment fragment = YourFragment.newInstance(myDate);
                       ft.replace(R.id.comments_fragment, fragment);
                       ft.commit();
                      }
                    }
                });
             }

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

            public void onDateSet(DatePicker view, int year, int month, int day) {
                 myDate = new MyDateObject(year, month, day); 
            }

        }
     }

    public class YourFragment extends Fragment {

        public YourFragment newInstance(MyDateObject myDate) {
            Bundle bundle = new Bundle();
            YourFragment fragment = new YourFragment();
            bundle.putInt("year", myDate.year);
            bundle.putInt("month", myDate.month);
            bundle.putInt("day", myDate.day);
            fragment.setArguments(bundle);
            return fragment;
        }
    }

就这些,解决你的问题?

试试这个:

MainActivity.java

public class MainActivity extends AppCompatActivity implements
        DatePickerFragment.DatePickerListener, TimePickerFragment.TimePickerListener
{
    private Calendar calendar;
    FragmentManager fm;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        calendar = Calendar.getInstance();

        fm = getSupportFragmentManager();
        DatePickerFragment dateDialog = new DatePickerFragment();
        dateDialog.show(fm, "fragment_date");
    }

    @Override
    public void onDateSet(int year, int month, int day)
    {
        // Set selected year, month and day in calendar object
        calendar.set(year, month, day);

        // Start Time dialog
        TimePickerFragment timeDialog = new TimePickerFragment();
        timeDialog.show(fm, "fragment_time");

    }

    @Override
    public void onTimeSet(int hourOfDay, int minute)
    {
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);

        // Here, your calendar object is ready.
    }
}

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
    public interface DatePickerListener
    {
        public void onDateSet(int year, int month, int day);
    }

    private DatePickerListener listener;

    @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 onAttach(Activity activity)
    {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            listener = (DatePickerListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    public void onDateSet(DatePicker view, int year, int month, int day)
    {
        listener.onDateSet(year, month, day);
    }
}

TimePickerFragment.java

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
    public interface TimePickerListener
    {
        public void onTimeSet(int hourOfDay, int minute);
    }

    private TimePickerListener listener;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        final Calendar c=Calendar.getInstance();
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minute=c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            listener = (TimePickerListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute)
    {
        listener.onTimeSet(hourOfDay, minute);
    }
}

希望这能解决您的问题。

我亲自测试过,确实有效。希望对你有帮助!

MainActivity.java

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public class TimePickerFragment extends DialogFragment implements
            TimePickerDialog.OnTimeSetListener 
            {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) 
        {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
        {
            // Do something with the time chosen by the user
            // Toast.makeText(MainActivity.this,String.valueOf(year) + "-" +
            // String.valueOf(monthOfYear) + "-" +
            // String.valueOf(dayOfMonth),Toast.LENGTH_LONG).show();
            String am_pm = "";
            Calendar datetime = Calendar.getInstance();
            datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            datetime.set(Calendar.MINUTE, minute);

            if (datetime.get(Calendar.AM_PM) == Calendar.AM)
                am_pm = "AM";
            else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
                am_pm = "PM";

            String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ? "12"
                    : datetime.get(Calendar.HOUR) + "";

            /*
             * ((Button) getActivity().findViewById(R.id.btnEventStartTime))
             * .setText(strHrsToShow + ":" + datetime.get(Calendar.MINUTE) + " "
             * + am_pm);
             */

            /*
             * Toast.makeText(MainActivity.this, "The selected time is: " +
             * String.valueOf(hourOfDay) + ":" + String.valueOf(minute) + " " +
             * am_pm, Toast.LENGTH_SHORT).show();
             */

            // This code converts 24 hour hand to 12 hour hand
            Toast.makeText(
                    MainActivity.this,
                    "The selected time is: " + String.valueOf(strHrsToShow)
                            + ":" + String.valueOf(minute) + " " + am_pm,
                    Toast.LENGTH_SHORT).show();
        }
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public class DatePickerFragment extends DialogFragment implements
            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);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            Toast.makeText(MainActivity.this, "The selected date is: " +
                    String.valueOf(day) + "." + String.valueOf(month) + "." + 
                    String.valueOf(year), Toast.LENGTH_SHORT).show();
        }

    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }
}    

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4863A0"
    tools:context="com.nikhil.pickers.MainActivity" >

    <Button
        android:id="@+id/pickTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="100dp"
        android:onClick="showTimePickerDialog"
        android:text="Pick Time" />

    <Button
        android:id="@+id/pickDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/pickTime"
        android:layout_alignLeft="@id/pickTime"
        android:onClick="showDatePickerDialog"
        android:text="Pick Date" />

</RelativeLayout>

您可以使用 listeners 来 link 您的 fragments 彼此。我通过为每个 fragment 添加一个侦听器来获取您所拥有的并对其进行了一些修改。然后我创建了一个 delegate 来管理两个 fragments 并将结果整齐地合并到一个 Calendar 对象中。您可以根据需要检索结果。可能和另一个听众在一起。

注意 从架构上讲,这不是最好的解决方案,因为我在几分钟内将它组合在一起。您可以移动内容以获得最适合场景的模式。

这是示例代码。


您可以像这样从您的 Activity 调用对话框

private void showDateTimeDialog() {
    final FragmentManager fm = getSupportFragmentManager();
    DateTimeDialog dateTimeDialog = new DateTimeDialog(this, fm);
    dateTimeDialog.show();
}

DateTimeDialog.java

import android.app.Activity;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;

import java.util.Calendar;

public class DateTimeDialog {

    private Activity activity;
    private DatePickerFragment datePickerFragment;
    private TimePickerFragment timePickerFragment;
    private FragmentManager fragmentManager;
    private Calendar calendar;

    public DateTimeDialog(Activity activity, FragmentManager fragmentManager) {
        this.activity = activity;
        this.fragmentManager = fragmentManager;

        this.calendar = Calendar.getInstance();
        this.datePickerFragment = new DatePickerFragment();
        this.timePickerFragment = new TimePickerFragment();

        this.datePickerFragment.setOnDateSelectedListener(getOnDateSelectedListener());
        this.timePickerFragment.setOnTimeSelectedListener(getOnTimeSelectedListener());
    }

    public void show() {
        datePickerFragment.show(fragmentManager, "datePickerFragment");
    }

    private TimePickerFragment.OnTimeSelectedListener getOnTimeSelectedListener() {
        return new TimePickerFragment.OnTimeSelectedListener() {

            @Override
            public void onTimeSelected(int hourOfDay, int minute) {
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);

                // Here you have your finished result.
                Toast.makeText(activity, calendar.getTime().toString(), Toast.LENGTH_LONG).show();
            }
        };
    }

    private DatePickerFragment.OnDateSelectedListener getOnDateSelectedListener() {
        return new DatePickerFragment.OnDateSelectedListener() {

            @Override
            public void onDateSelected(int year, int monthOfYear, int dayOfMonth) {
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                timePickerFragment.show(fragmentManager, "timePickerFragment");
            }
        };
    }
}

DatePickerFragment.java

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

import java.util.Calendar;

public class DatePickerFragment
        extends DialogFragment implements DatePickerDialog.OnDateSetListener {

    private OnDateSelectedListener onDateSelectedListener;

    public void setOnDateSelectedListener(OnDateSelectedListener onDateSelectedListener) {
        this.onDateSelectedListener = onDateSelectedListener;
    }

    @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 view, int year, int monthOfYear, int dayOfMonth) {
        onDateSelectedListener.onDateSelected(year, monthOfYear, dayOfMonth);
    }

    public interface OnDateSelectedListener {
        void onDateSelected(int year, int monthOfYear, int dayOfMonth);
    }
}

TimePickerFragment.java

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;

import java.util.Calendar;

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    private OnTimeSelectedListener onTimeSelectedListener;

    public void setOnTimeSelectedListener(OnTimeSelectedListener onTimeSelectedListener) {
        this.onTimeSelectedListener = onTimeSelectedListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c=Calendar.getInstance();
        int hour=c.get(Calendar.HOUR_OF_DAY);
        int minute=c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(),this,hour,minute, DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        onTimeSelectedListener.onTimeSelected(hourOfDay, minute);
    }

    public interface OnTimeSelectedListener {
        void onTimeSelected(int hourOfDay, int minute);
    }
}