Android Studio:如何从datepicker和时间选择器获取日期并在屏幕上显示?

时间:2015-04-29 09:51:48

标签: android android-studio datepicker

Android Studio:如何从datepicker和时间选择器获取日期并在屏幕上显示为永久文本(不是toast)?

public class DialogHandlerDate extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        DateSettings dateSettings = new DateSettings(getActivity());
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog;
        dialog = new DatePickerDialog(getActivity(),dateSettings,year,month,day);
        return dialog;
        //return super.onCreateDialog(savedInstanceState);
    }
}

日期设置活动:

public class DateSettings implements DatePickerDialog.OnDateSetListener {

    Context context;
    public DateSettings(Context context){
        this.context=context;
    }
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Toast.makeText(context,"Selected date:"+monthOfYear+" / "+dayOfMonth+" / "+year,Toast.LENGTH_LONG).show();
        CharSequence text = ""+dayOfMonth+"-"+""+monthOfYear+"-"+"" +year;
        int duration=Toast.LENGTH_SHORT;
        Toast toast= Toast.makeText(context,text,duration);
        toast.show();
    }

}

3 个答案:

答案 0 :(得分:1)

这是我的代码,您可以在MainActivity上实现它,并将片段放在OnClickListener上以获取相应的Set Date / Time:

private TextView mDateDisplay;
private int mYear;
private int mMonth;
private int mDay;

// Capture UI elements
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);

// Put this on your OnClickListener for the "Change the Date"
// Create a new DatePickerFragment
DialogFragment newFragment = new DatePickerFragment();
// Display DatePickerFragment
newFragment.show(getFragmentManager(), "DatePicker");

// Callback called when user sets the date
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    mYear = year;
    mMonth = monthOfYear;
    mDay = dayOfMonth;
    updateDate();
}

// Update the date String in the TextView
private void updateDate() {
    mDateDisplay.setText(new StringBuilder()
        // Month is 0 based so add 1
        .append(mMonth + 1).append("-").append(mDay).append("-")
        .append(mYear).append(" "));
}

public static class DatePickerFragment extends DialogFragment implements OnDateSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Set the current date in the DatePickerFragment
        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);
    }

    // Callback to DatePickerActivity.onDateSet() to update the UI
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        ((OnDateSetListener) getActivity()).onDateSet(view, year, monthOfYear, dayOfMonth);
    }
}

Set Time也是如此:

private TextView mTimeDisplay;
private int mHour;
private int mMinute;

// Capture UI elements
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);

// Put this on your OnClickListener for the "Change the Time"
// Create a new TimePickerFragment
DialogFragment newFragment = new TimePickerFragment();
// Display DatePickerFragment
newFragment.show(getFragmentManager(), "TimePicker");

// Callback called when user sets the time
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    mHour = hourOfDay;
    mMinute = minute;
    updateTime();
}

// Update the time String in the TextView
private void updateTime() {
mTimeDisplay.setText(new StringBuilder().append(pad(mHour)).append(":")
    .append(pad(mMinute)));
}

// Prepends a "0" to 1-digit minutes
private static String pad(int c) {
    if (c >= 10){
        return String.valueOf(c);
    } else{
        return"0"+String.valueOf(c);
    }
}

public static class TimePickerFragment extends DialogFragment implements OnTimeSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int hourOfDay = 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, hourOfDay, minute, false);
    }

    // Callback to TimePickerFragmentActivity.onTimeSet() to update the UI
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        ((OnTimeSetListener) getActivity()).onTimeSet(view, hourOfDay, minute);
    }
}

您可以进一步查看此资源链接: DatePicker | Android Developers

答案 1 :(得分:0)

 @Override
        protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_update_task);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            initializeCalendar();
        }

    private void initializeCalendar() {
        calendar.setShowWeekNumber(false);
        calendar.setFirstDayOfWeek(2);
        calendar.setDate(lDate);

        calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener({

  @Override
     public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
                Toast.makeText(getApplicationContext(), month+1 + "/" + day  + "/" + year, Toast.LENGTH_SHORT).show();
              String calDate = month+1 + "/" + day + "/" + year;
            }
        });
    }

答案 2 :(得分:0)

我将逐步解释。

第1步:创建Timepicker和DatePicker

第2步: - 在某个Button或edittext上设置ClickListener以启动timepicker和datepicker

步骤3: - 在TimepickerFragment和DatepickerFragment中声明接口(给定示例中的OnTimeChangeListenerInterface和OnDateChangeListenerInterface)

步骤4: - 在MainActivity中实现上述接口,并覆盖onTimeChangeListener和onDateChangeListener方法以接收选定的时间和日期。

1。 MainActivity.java

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements 
             TimePickerFragment.OnTimeChangeListenerInterface,
             DatePickerFragment.OnDateChangeListenerInterface{

    private EditText timeEditText;
    private EditText dateEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        timeEditText = (EditText) findViewById(R.id.time_edit_text);
        dateEditText = (EditText) findViewById(R.id.date_edit_text);

        timeEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment timePickerFragment = new TimePickerFragment();
                timePickerFragment.show(getSupportFragmentManager(), "timePicker");
            }
        });

        dateEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment datePickerFragment = new DatePickerFragment();
                datePickerFragment.show(getSupportFragmentManager(), "datePicker");
            }
        });

        // method from OnTimeChangeListenerInterface, this method will be called when user select time from time picker
        @Override
        public void onTimeChangeListener(String time) {
            timeEditText.setText(time);    // set time to the edittext
        }

        // method from OnDateChangeListenerInterface, this method will be called when user select the date
        @Override
        public void onDateChangeListener(String date) {
            dateEditText.setText(date);    // set date to edittext
        }
    }

}

xml文件: -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    android:paddingTop="50dp"
    tools:context="ad.abc.com.datetimepicker.MainActivity">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="50dp"
        android:id="@+id/time_edit_text"
        android:focusable="false"
        android:hint="Time" />

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/date_edit_text"
        android:focusable="false"
        android:hint="Date"/>

</LinearLayout>

点击timeEditText和DateEditText将分别启动时间选择器和日期选择器。 timepicker和datepicker片段的代码将在下一步中进行。

2。 TimePicker的代码

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{

    // declaration of interface, need to be implemented in MainActivity
    public interface OnTimeChangeListenerInterface{
        void onTimeChangeListener(String time);    // this method needs to be override in MainActivity to get the value of selected 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()));
    }

    // callback to the onTimeChangeListener method in MainActivity to pass value of selected time
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // passing selected value to the MainActivity through onTimeChangeListener method
        ((OnTimeChangeListenerInterface) getActivity()).onTimeChangeListener(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
    }

}

同样,对于DatePicker

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{

    public interface OnDateChangeListenerInterface{
        void onDateChangeListener(String date);
    }

    @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 month, int dayOfMonth) {
        // passing selected value to the MainActivity through onDateChangeListener method
        ((OnDateChangeListenerInterface) getActivity()).onDateChangeListener(String.valueOf(dayOfMonth) + "-" + String.valueOf(month) + "-" + String.valueOf(year));
    }
}