实现功能
实现日期和时间选择的对话框,具体效果可看下图(以日期为例)
具体代码
1 日期对话框
1.1 xml
1.2 Java
package com.example.learn; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.DatePicker; import android.widget.TextView; import java.util.Calendar; public class DatePickerActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener { private TextView tv; private DatePicker dp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_date_picker); findViewById(R.id.btn_ok).setOnClickListener(this); findViewById(R.id.btn_date).setOnClickListener(this); tv=findViewById(R.id.tv_date); dp = findViewById(R.id.datePicker); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.btn_ok: String desc=String.format("%d年%d月%d日",dp.getYear(),dp.getMonth()+1,dp.getDayOfMonth()); tv.setText(desc); break; case R.id.btn_date: //获取当前时间 Calendar now = Calendar.getInstance(); DatePickerDialog dpd = new DatePickerDialog(this,this,now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH)); //显示 dpd.show(); break; } } @Override public void onDateSet(DatePicker datePicker, int i, int i1, int i2) { String desc=String.format("%d年%d月%d日",i,i1+1,i2); tv.setText(desc); } }
2 时间选择对话框
2.1 xml
2.2 java
package com.example.learn; import androidx.appcompat.app.AppCompatActivity; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import java.util.Calendar; public class TimePickerActivity extends AppCompatActivity implements View.OnClickListener, TimePickerDialog.OnTimeSetListener { private TextView tv; private TimePicker tp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_time_picker); findViewById(R.id.btn_ok).setOnClickListener(this); findViewById(R.id.btn_time).setOnClickListener(this); tv=findViewById(R.id.tv_date); tp = findViewById(R.id.timePicker); } @Override public void onClick(View view) { switch(view.getId()){ case R.id.btn_ok: String desc=String.format("%d时%d分",tp.getCurrentHour(),tp.getCurrentMinute()); tv.setText(desc); break; case R.id.btn_time: //获取日历实例,包含日期和时分 Calendar instance = Calendar.getInstance(); //构建时间对话框 // TimePickerDialog tpd = new TimePickerDialog(this,this, // instance.get(Calendar.HOUR_OF_DAY), // instance.get(Calendar.MINUTE), // true); //添加样式 TimePickerDialog tpd = new TimePickerDialog(this, android.R.style.Theme_Holo_Dialog,this, instance.get(Calendar.HOUR_OF_DAY), instance.get(Calendar.MINUTE), true); tpd.show(); break; } } @Override public void onTimeSet(TimePicker timePicker, int i, int i1) { String desc=String.format("%d时%d分",i,i1); tv.setText(desc); } }
还没有评论,来说两句吧...