之前的:
旧版时间控件博客-王睿
替换后:
是不是感觉更加美观些,其实代码比之前的还要很简单,大家往下看:
activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
<DatePicker
android:id="@+id/dp_time"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="100dp"
android:datePickerMode="spinner"
android:layout_centerInParent="true"
android:calendarViewShown="false"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private DatePicker dpTime;
private String time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dpTime = findViewById(R.id.dp_time);
// init方法,第1~3参数分别表示:年,月,日,第四个参数是:一个DatePicker 时间控件的对象
// 再调用OnDateChangedListener()方法,就可以达到时刻监听的效果
dpTime.init(2019, 9, 4, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
time = ""+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日";
Toast.makeText(MainActivity.this,"时间为:"+time,Toast.LENGTH_LONG).show();
}
});
}
}