日期和时间选择器
一、日期选择器
视图代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity2_DateActivity">
<DatePicker
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/dp" />
</LinearLayout>
Java代码:
package com.example.androiddialog26;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity2_DateActivity extends AppCompatActivity {
private DatePicker dp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2__date);
dp = findViewById(R.id.dp);
Calendar calendar=Calendar.getInstance();
dp.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Toast.makeText(MainActivity2_DateActivity.this,year+"年"+(monthOfYear+1)+"月"+dayOfMonth,Toast.LENGTH_SHORT).show();
}
});
}
}
效果:
二、时间选择器
视图代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity3_TimeActivity">
<TimePicker
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tp" />
</LinearLayout>
Java代码:
package com.example.androiddialog26;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity3_TimeActivity extends AppCompatActivity {
private TimePicker tp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3__time);
tp = findViewById(R.id.tp);
tp.setIs24HourView(true);
tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(MainActivity3_TimeActivity.this,hourOfDay+":"+minute,Toast.LENGTH_SHORT).show();
}
});
}
}
效果: