附上代码:
xml部分
Activity.java部分
package com.example.urien.secondapp;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class Lesson7_Activity extends AppCompatActivity {
//第一步:声明控件
private TimePicker timePicker;
private Button buttonTimemode;
private Button buttonTimepickmode;
private Button buttonGettime;
private TextView textViewTime;
private DatePicker datePicker;
private Button buttonDadepickmode;
private Button buttonGetdate;
private TextView textViewDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson7_);
//第二步:找到控件
timePicker = findViewById(R.id.L7_timepick);
buttonTimemode = findViewById(R.id.L7_bt_timemode);
buttonTimepickmode = findViewById(R.id.L7_timepickmode);
buttonGettime = findViewById(R.id.L7_bt_gettime);
textViewTime = findViewById(R.id.L7_texttime);
datePicker = findViewById(R.id.L7_datapick);
buttonDadepickmode = findViewById(R.id.L7_bt_dadepicmode);
buttonGetdate = findViewById(R.id.L7_bt_getdate);
textViewDate = findViewById(R.id.L7_textdate);
//第四步:设置监听器
timePicker.setOnTimeChangedListener(new TimeListener());
buttonTimemode.setOnClickListener(new ButtonListnner());
buttonGettime.setOnClickListener(new ButtonListnner());
buttonGetdate.setOnClickListener(new ButtonListnner());
}
//第三步:实现监听器函数接口
class TimeListener implements TimePicker.OnTimeChangedListener{
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
System.out.println("Hour:" + hourOfDay + ",minute:" + minute);
textViewTime.setText(hourOfDay + ":" + minute);
}
}
class ButtonListnner implements View.OnClickListener{
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.L7_bt_timemode:
if(buttonTimemode.getText().toString().contains("12")){
timePicker.setIs24HourView(false);
buttonTimemode.setText("24小时制");
}
else{
timePicker.setIs24HourView(true);
buttonTimemode.setText("12小时制");
}
break;
case R.id.L7_bt_gettime:
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
textViewTime.setText(hour + ":" + minute);
break;
case R.id.L7_bt_getdate:
int year = datePicker.getYear()+1;
int month = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
textViewDate.setText(year + "年" + month + "月" + day + "日");
break;
}
}
}
}
By Urien 2018年5月31日 23:41:59