TimePikcer的实现:
通过OnTimeChangedListener()方法中的OnTimeChanged方法实现。
实例代码如下:
public class MainActivity extends Activity {
private TimePicker tp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tp=(TimePicker)findViewById(R.id.tp);
//设置时间是否为24小时制,true代表24小时制,false代表上下午
tp.setIs24HourView(true);
//设置OnTimeChangedListener监听器,实现onTimeChanged方法
tp.setOnTimeChangedListener(new OnTimeChangedListener(){
//getCurrentHour()得到小时,getCurrentMinute()得到分钟
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(MainActivity.this,"现在时间是" +tp.getCurrentHour() +":" + pad(tp.getCurrentMinute()),Toast.LENGTH_SHORT).show();
}
});
}
private static String pad(int c){
if(c>=10){
return String.valueOf(c);
}
else{
return "0"+String.valueOf(c);
}
}
}
效果图:
效果图:设置时间为12:03
TimePickerDialog实现:
1.初始化Calendar,Calendar c=Calendar.getInstance()
2.用Calendar对象调用get方法得到当前的小时和分钟
mHour=c.get(Calendar.HOUR_OF_DAY);
mMinute=c.get(Calendar.MINUTE);
3.设置button监听器,在监听器内创建TimePickerDialog对话框,点击弹出TimePickerDialog
settime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog tpd=new TimePickerDialog(MainActivity.this, mTimesetlistener, mHour, mMinute, true);
tpd.show();
}
});
4.设置TimePickerDialog监听器
private TimePickerDialog.OnTimeSetListener mTimesetlistener=new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute=minute;
updateDisplay();
}
};
注意这里的监听器名称和上面创建的TimePickerDialog对象的监听参数一致,都是mTimesetlistener。
5.定义updateDisplay()方法
完整的代码如下:
public class MainActivity extends Activity {
private TextView showtime;
private Button settime;
int mHour;
int mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showtime=(TextView)findViewById(R.id.showtime);
settime=(Button)findViewById(R.id.settime);
Calendar c=Calendar.getInstance();
mHour=c.get(Calendar.HOUR_OF_DAY);
mMinute=c.get(Calendar.MINUTE);
showtime.setText("现在时间是"+mHour+":"+mMinute);
settime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TimePickerDialog tpd=new TimePickerDialog(MainActivity.this, mTimesetlistener, mHour, mMinute, true);
tpd.show();
}
});
}
private TimePickerDialog.OnTimeSetListener mTimesetlistener=new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour=hourOfDay;
mMinute=minute;
updateDisplay();
}
};
private void updateDisplay(){
showtime.setText("现在时间是"+new StringBuilder().append(mHour).append(":").append(mMinute));
}
}
效果图:刚启动的界面
效果图:点击设置时间,设置为12:11
效果图:设置完成后