安卓学习-日历选择器和时间选择器

日历选择器和时间选择器

日历选择器的时间选择器是通过调整钟表和日历来实现日期时间更改的方法,分别对应DatePicker 与 TimePicker

步骤1
编写布局文件


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.project.zero.timepicker.MainActivity">

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"

        />


LinearLayout>

步骤2
编写代码
1利用settitle改变标题来测试改变指针所对应时间
2月份的记录是从0开始的,所以要显示正常需要+1
3更改年月日 触发OnDateChangedListener 的 onDateChange事件
更改TimePicker时,分时触发OnTimeChangedListener 的onTimeChanged事件
利用calendar获取日历对象

public class MainActivity extends AppCompatActivity {

    private TimePicker mTimePicker;
    private DatePicker mDatePicker;
    private Calendar mCalendar;
    private int myear;
    private int mday;
    private int mmonth;
    private int mhour;
    private int mminute;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCalendar = Calendar.getInstance();
        myear = mCalendar.get(Calendar.YEAR);
        mmonth = mCalendar.get(Calendar.MONTH)+1;//因为获取的月份是从0开始记,所以要加1
        mday = mCalendar.get(Calendar.DAY_OF_MONTH);
        mhour = mCalendar.get(Calendar.HOUR);
        mminute = mCalendar.get(Calendar.MINUTE);
        setTitle(myear + "-" + mmonth + "-" + mday + "-" + mhour + ":" + mminute);

        mDatePicker = findViewById(R.id.datePicker);
        mTimePicker = findViewById(R.id.timePicker);
        mDatePicker.init(myear, mmonth-1, mday, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                myear = year;
                mmonth = monthOfYear + 1;
                mday = dayOfMonth;
                setTitle(myear + "-" + mmonth + "-" + mday + "-" + mhour + ":" + mminute);
            }
        });

        mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                mminute = minute;
                mhour = hourOfDay;
                setTitle(myear + "-" + mmonth + "-" + mday + "-" + mhour + ":" + mminute);

            }
        });
    }
}

效果截图
安卓学习-日历选择器和时间选择器_第1张图片

你可能感兴趣的:(安卓学习笔记)