android studio 已經有內建的日期元件了,我們知將他引用即可
第一步:在局文件創一個 button 和 textview
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<TextView
android:id="@+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/databtn"
android:layout_width="168dp"
android:layout_height="76dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
第二步:把佈局文件與主程式連結
package com.example.data;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView data;
private String online_date;
private Button databtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = findViewById(R.id.data);
databtn = findViewById(R.id.databtn);
databtn.setOnClickListener(this);
}
第三步:當按鈕被按下時,顯示日歷
@Override
public void onClick(View view) {
Calendar c = Calendar.getInstance();
new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
data.setText(year+"/"+(monthOfYear+1)+"/"+dayOfMonth);
online_date=year+"/"+(monthOfYear+1)+"/"+dayOfMonth;
}
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
data.setText(online_date);
}