时间:2022-10-08 12:54:27 | 栏目:Android代码 | 点击:次
一、简介
二、方法
最日常的使用方法了
日期控件DatePicker
时间控件TimePicker
月份从0开始
三、代码实例
效果图:
代码:
fry.Activity01
package fry; import com.example.DatePicherDemo1.R; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; import android.widget.Toast; public class Activity01 extends Activity implements OnDateChangedListener,OnTimeChangedListener{ private DatePicker datePicker1; private TimePicker timePicker1; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity01); setTitle("时间日期控件测试"); datePicker1=(DatePicker) findViewById(R.id.datePicker1); timePicker1=(TimePicker) findViewById(R.id.timePicker1); //初始化日期,并设置日期被改变后的监听事件 datePicker1.init(2017, 8, 7, this); //设置时间以24小时制 timePicker1.setIs24HourView(true); //设置时间被改变后的监听时间 timePicker1.setOnTimeChangedListener(this); } @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub Toast.makeText(this, "日期被改变为: "+year+"."+(monthOfYear+1)+"."+dayOfMonth, Toast.LENGTH_SHORT).show(); } @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub Toast.makeText(this, "时间被改变为: "+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show(); } }
/DatePicherDemo1/res/layout/activity01.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <DatePicker android:id="@+id/datePicker1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TimePicker android:id="@+id/timePicker1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
四、收获
1、初始化日期,并设置日期被改变后的监听事件
datePicker1.init(2017, 8, 7, this);
2、设置时间以24小时制
timePicker1.setIs24HourView(true);
3、设置时间被改变后的监听事件
timePicker1.setOnTimeChangedListener(this);
总结