Calendar(日历)--选择日期

Calendar(日历)--选择日期_第1张图片


content_main.xml布局



    
    
    
    
    
    
   


用DatePicker和TimePicker
package com.eson.mycalendar ;

import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.widget.DatePicker ;
import android.widget.EditText ;
import android.widget.TimePicker ;

import java.util.Calendar ;

public class ChooseDate extends AppCompatActivity {

    private DatePicker datePicker;
    private TimePicker timePicker ;
    private int year ;
    private int month ;
    private int day ;
    private int hour ;
    private int minute ;

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

        datePicker = (DatePicker)findViewById(R.id. datePicker );
        timePicker = (TimePicker) findViewById(R.id. timePicker );
        //获取当前的年,月,日,小时,分钟
        Calendar c=Calendar. getInstance() ;
        year = c.get(Calendar. YEAR) ;
        month = c.get(Calendar. MONTH) ;
        day = c.get(Calendar. DAY_OF_MONTH) ;
        hour = c.get(Calendar. HOUR) ;
        minute = c.get(Calendar. MINUTE) ;
        //初始化DatePicker组件,初始化时指定监听器
        datePicker .init( year, month , day , new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged (DatePicker view, int year , int month , int day) {

                ChooseDate. this. year =year;
                ChooseDate.this . month=month ;
                ChooseDate.this . day=day ;
                //显示当前日期,时间
                showDate(year, month ,day , hour, minute );
            }

        });
        timePicker .setOnTimeChangedListener( new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged (TimePicker view, int hourOfDay , int minute) {
                ChooseDate. this. hour =hourOfDay;
                ChooseDate.this . minute=minute ;
                //显示当前日期,时间
                showDate(year , month, day ,hour , minute);
            }
        });

    }

    //定义在EditText中显示当前日期,时间的方法
    private void showDate (int year , int month , int day, int hour , int minute) {

        EditText show= (EditText) findViewById(R.id. show) ;
        show.setText( "您购买日期为:" +year+ "年"+(month+ 1 )+"月" +day+ "日"+hour+ "时" +minute+"分" ) ;
    }
}




你可能感兴趣的:(Calendar(日历)--选择日期)