3.27

所花时间(包括上课):1

打码量(行):100

博客量(篇):1

了解到知识点:学习日期对话框DatePickerDialog

import android.app.DatePickerDialog;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.DatePicker;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

 

public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

 

    private Button showDatePickerButton;

    private Calendar calendar;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        showDatePickerButton = findViewById(R.id.btn_show_date_picker);

        calendar = Calendar.getInstance();

 

        showDatePickerButton.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                int year = calendar.get(Calendar.YEAR);

                int month = calendar.get(Calendar.MONTH);

                int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

 

                // 创建一个新的 DatePickerDialog 对象

                DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,

                        MainActivity.this, year, month, dayOfMonth);

 

                // 显示日期选择器对话框

                datePickerDialog.show();

            }

        });

    }

 

    @Override

    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

        // 当用户选择日期时触发该方法

        String selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;

        Toast.makeText(MainActivity.this, "Selected date: " + selectedDate, Toast.LENGTH_SHORT).show();

    }

}

<!-- activity_main.xml -->

<Button

    android:id="@+id/btn_show_date_picker"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="Show Date Picker" />

posted @ 2024-03-27 21:41  赵千万  阅读(4)  评论(0编辑  收藏  举报