日期和时间选择器(DatePicker与TimePicker的用法)

时间:2022-06-03 18:08:58
//--------安卓的日期和时间选择器(DatePicker与TimePicker的用法),点击获取所选择的时间和日期
@SuppressLint("ResourceAsColor")
public class MainActivity extends Activity {

private EditText dateEt=null;
    private EditText timeEt=null;
    


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

dateEt=(EditText)findViewById(R.id.dateEt);
        timeEt=(EditText)findViewById(R.id.timeEt);
        DatePicker datePicker=(DatePicker)findViewById(R.id.datePicker);
        TimePicker timePicker=(TimePicker)findViewById(R.id.timePicker);
        Calendar calendar=Calendar.getInstance();
        int year=calendar.get(Calendar.YEAR);
        int monthOfYear=calendar.get(Calendar.MONTH);
        int dayOfMonth=calendar.get(Calendar.DAY_OF_MONTH);
        int hourOfDay=calendar.get(Calendar.HOUR_OF_DAY);
        int minute=calendar.get(Calendar.MINUTE);
        dateEt.setText("您选择的日期是:"+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日。");
        timeEt.setText("您选择的时间是:"+hourOfDay+"时"+minute+"分。");
        
        datePicker.init(year, monthOfYear, dayOfMonth, new OnDateChangedListener(){


            public void onDateChanged(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) {
            //dateEt.setTextColor(R.color.red);
                dateEt.setText("您选择的日期是:"+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日。");
            }
            
        });
        
        timePicker.setOnTimeChangedListener(new OnTimeChangedListener(){


            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            // timeEt.setTextColor(R.color.red);
                timeEt.setText("您选择的时间是:"+hourOfDay+"时"+minute+"分。");
            }
            
        });
}

}

//布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <DatePicker android:id="@+id/datePicker" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="true"
        android:layout_gravity="center_horizontal"/>
    <EditText android:id="@+id/dateEt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:editable="false"/>
    <TimePicker android:id="@+id/timePicker" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>
    <EditText android:id="@+id/timeEt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:editable="false"/>
</LinearLayout>

日期和时间选择器(DatePicker与TimePicker的用法)