引言
通常我们都会在软件中遇到时间选择器功能,选择“年-月-日”,今天就来使用PickerView控件来实现这个功能。国际惯例,先上效果!
效果预览
用法
第一步:添加依赖(app下build.gradle中)
//PickerView库
implementation 'com.contrarywind:Android-PickerView:4.1.9'
第二步:布局文件
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".blog.Case46"
tools:ignore="MissingConstraints">
<Button
android:id="@+id/btnTimePicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@color/green"
android:text="时间选择器"
android:textColor="@color/white"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
</androidx.constraintlayout.widget.ConstraintLayout>
第三步:在Activity中书写业务逻辑
public class Case46 extends AppCompatActivity {
private Button btnTimePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_case46);
//初始化
initView();
getView1();
}
private void initView(){
btnTimePicker = findViewById(R.id.btnTimePicker);
btnAreaPicker = findViewById(R.id.btnAreaPicker);
}
private void getView1(){
btnTimePicker.setOnClickListener((View)->{
timePicker();
});
}
//时间选择器
private void timePicker(){
//时间选择器
TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
ToastUtils.show(getTime(date));
}
}).build();
pvTime.setDate(Calendar.getInstance());//注:根据需求来决定是否使用该方法(一般是精确到秒的情况),此项可以在弹出选择器的时候重新设置当前时间,避免在初始化之后由于时间已经设定,导致选中时间与当前时间不匹配的问题。
pvTime.show();
}
//根据需要自行截取数据显示
private String getTime(Date date) {//可根据需要自行截取数据显示
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(date);
}
}