本文SDK版本 Android SDK 4.2.2
今天为大家介绍Android中的时间控件(TimePicker),要在Android中使用时间控件(TimePicker)先要在布局文件中声明。
<TimePicker android:id="@+id/time1" android:layout_width="match_parent" android:layout_height="wrap_content" />
声明非常简单,如果我们要获取用户选择的时间则需要使用 OnTimeChangedListener来监听
Java代码如下:
package com.zhoucj.helloworlddemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; public class TimePickerActivity extends Activity { TimePicker timePicker; private static String TAG="TimePickerActivity"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.timepicker); timePicker=(TimePicker)findViewById(R.id.time1); timePicker.setOnTimeChangedListener(new OnTimePickerChange()); } class OnTimePickerChange implements OnTimeChangedListener { /** * view:该对象代表TimePicker * hourOfDay:用户选择的小时 * minute:用户所选择的分钟 */ @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Log.i(TAG, "时="+hourOfDay+"--分="+minute); } } }
这个时间看着有点别扭,我们希望是24小时制的时间,很简单,在Java代码中设置即可:
//设置是否使用24小时制显示时间 timePicker.setIs24HourView(true);
如果我们希望当用户点击按钮的时候获取时间
package com.zhoucj.helloworlddemo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; public class TimePickerActivity extends Activity { TimePicker timePicker; Button button1; private static String TAG="TimePickerActivity"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.timepicker); timePicker=(TimePicker)findViewById(R.id.time1); //设置是否使用24小时制显示时间 timePicker.setIs24HourView(true); timePicker.setOnTimeChangedListener(new OnTimePickerChange()); button1=(Button)findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "时:"+timePicker.getCurrentHour()+",分钟:"+timePicker.getCurrentMinute()); } }); } class OnTimePickerChange implements OnTimeChangedListener { /** * view:该对象代表TimePicker * hourOfDay:用户选择的小时 * minute:用户所选择的分钟 */ @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Log.i(TAG, "时="+hourOfDay+"--分="+minute); } } }
如果我们是设置TimePicker的时间
timePicker.setCurrentHour(12); timePicker.setCurrentMinute(12);
好了,今天就简单的介绍下 时间控件(TimePicker);
最后祝大家 工作顺利,学习进步。