【问题标题】:How to get date and time from Date/Time Picker dialog and show it?如何从日期/时间选择器对话框中获取日期和时间并显示它?
【发布时间】:2017-12-30 05:34:39
【问题描述】:
        public class MainActivity extends FragmentActivity {

        TextView dateView, timeView;
        String date;

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

            dateView = (TextView) findViewById(R.id.dateTextID);
            timeView = (TextView) findViewById(R.id.timeTextID);

        }

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

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

        //*******************************************//
        //DATE PICKER CLASS
        public static 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(), (DatePickerDialog.OnDateSetListener)getActivity(), year, month, day);
            }

            public void onDateSet(DatePicker view, int year, int month, int day) {
                // Do something with the date chosen by the user
                String date =Integer.toString(day)+"/"+Integer.toString(month)+"/"+Integer.toString(yeat);
                dateView.setText(date);
            }
        }
        //*******************************************//
        //TIME PICKER CLASS
        public static 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
            }
        }

    }

我想设置 dateView 和 timeView(都是 TextView)来显示用户选择的日期和时间,但问题是我不能在 onDateSet 和 onTimeSet 方法中做任何事情,因为它们是静态的。

在 onDateSet() 中:

String date =Integer.toString(day)+"/"+Integer.toString(month)+"/"+Integer.toString(yeat); dateView.setText(date);

这会导致无法从静态上下文中引用非静态字段 dateView 的错误。如何解决。我寻找了类似的问题,但它们都只是 DatePickerFragment 而不是同一班级的日期和时间。 这是我用于布局的 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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showDatePickerDialog"
        android:text="@string/date_button_set"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/dateTextID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/date_selected"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="54dp"
        android:layout_marginStart="54dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showTimePickerDialog"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignStart="@+id/button1"
        android:layout_below="@+id/button1"
        android:text="@string/time_button_set" />

    <TextView
        android:id="@+id/timeTextID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button"
        android:layout_alignLeft="@+id/dateTextID"
        android:layout_alignStart="@+id/dateTextID" />

</RelativeLayout>

【问题讨论】:

    标签: java android date time fragment


    【解决方案1】:

    时间选择器

    final Calendar getDate = Calendar.getInstance();
        TimePickerDialog timePickerDialog = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                getDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
                getDate.set(Calendar.MINUTE, minute);
                SimpleDateFormat timeformat=new SimpleDateFormat("HH:mm a");
                timeFormat.format(getDate.getTime()));
            }
        }, getDate.get(Calendar.HOUR_OF_DAY), getDate.get(Calendar.MINUTE), false);
        timePickerDialog.show()
    

    日期选择器

    final Calendar getDate = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                getDate.set(year, monthOfYear, dayOfMonth);
           SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
                    format.format(getDate.getTime());
            }
        }, getDate.get(Calendar.YEAR),
                getDate.get(Calendar.MONTH),
                getDate.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    

    【讨论】:

      【解决方案2】:

      使用接口将设置的日期和时间传达回活动。

      public class MainActivity extends FragmentActivity implements
          DatePickerFragment.DatePickedListener, TimePickerFragment.TimePickedListener {
      
          TextView dateView, timeView;
          String date;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              dateView = (TextView) findViewById(R.id.dateTextID);
              timeView = (TextView) findViewById(R.id.timeTextID);
      
          }
      
          public void showDatePickerDialog(View v) {
              DialogFragment newFragment = new DatePickerFragment();
              newFragment.show(getFragmentManager(), "datePicker");
          }
      
          public void showTimePickerDialog(View v) {
              DialogFragment newFragment = new TimePickerFragment();
              newFragment.show(getFragmentManager(), "timePicker");
          }
      
          @Override
          public void onDatePicked(String date) {
              dateView.setText(date);
          }
      
          @Override
          public void onTimeSet(String time) {
              timeView.setText(time);
          }
      }
      

      日期选择器类

      public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
      
          private static final String TAG = "DatePickerFragment";
      
          private SimpleDateFormat dateFormatterEntry = new SimpleDateFormat("M/dd/yyyy");
          private Calendar calendar;
          int year;
          int month;
          int day;
      
          private DatePickedListener listener;
      
          public static interface DatePickedListener {
              void onDatePicked(String date);
          }
      
          @Override
          @NonNull
          public Dialog onCreateDialog(Bundle savedInstanceState) {
              Log.i(TAG, "onCreateDialog");
      
              calendar = Calendar.getInstance();
              year = calendar.get(Calendar.YEAR);
              month = calendar.get(Calendar.MONTH);
              day = calendar.get(Calendar.DAY_OF_MONTH);
      
              listener = (DatePickedListener) getActivity();
      
              return new DatePickerDialog(getActivity(), this, year, month, day);
          }
      
          @Override
          public void onDateSet(DatePicker view, int year, int month, int day) {
              calendar.set(year, month, day, 0, 0);
              String formattedDate = dateFormatterEntry.format(calendar.getTime());
              Log.i(TAG, formattedDate);
              listener.onDatePicked(formattedDate);
          }
      }
      

      对 TimePicker 做同样的事情并添加接口

      public class TimePickerFragment extends DialogFragment
                  implements TimePickerDialog.OnTimeSetListener {
      
              private TimePickedListener listener;
      
              public static interface TimePickedListener {
                  void onTimePicked(String time);
              }
      
              @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) {
                  listener.onDatePicked(Integer.toString(hourOfDay));
              }
          }
      

      【讨论】:

      • 您的答案有效!谢谢你。还有一个问题,我应该将 Date 和 TimePickerFragment 保留为不同的文件还是放在 MainActivity 类中
      • 我认为将 DatePicker 和 TimePicker 保存在不同的文件中以更好地组织和可读性是个好主意!
      【解决方案3】:

      您可以定义一个静态 TextView(我知道它会导致内存泄漏)和 onDateSet 方法获取 Date 并将其设置为 textview

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-06
        • 1970-01-01
        相关资源
        最近更新 更多