3.19

安卓datepicker
• 所花时间:3
• 代码行数:423
• 博客容量:1
• 代码如下:

package com.example.chapter06;

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.TextView;

import java.text.Format;
import java.util.Calendar;

public class datePiker extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {

    private TextView tvdate;
    private Button dppiker;
    private DatePicker dpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_piker);
        dpdate=findViewById(R.id.dpdate);

        dppiker = findViewById(R.id.bt_datepiker);
        tvdate = findViewById(R.id.tv_date);
        findViewById(R.id.bt_selectDate).setOnClickListener(this);
        dppiker.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.bt_datepiker){
            String desc= String.format("您选择的时期是%d年%d月%d日",dpdate.getYear(),dpdate.getMonth(),dpdate.getDayOfMonth());
            tvdate.setText(desc);
        }
        if(v.getId()==R.id.bt_selectDate){
            Calendar calendar =Calendar.getInstance();
            DatePickerDialog datePickerDialog=new DatePickerDialog(this,this,calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show();
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        String desc= String.format("您选择的时期是%d年%d月%d日",year,month,dayOfMonth);
        tvdate.setText(desc);
    }
}

<?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"
    android:orientation="vertical"
    android:padding="5dp">

    <DatePicker
        android:id="@+id/dpdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
        android:datePickerMode="spinner"/>

    <Button
        android:id="@+id/bt_datepiker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="提交"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv_date"/>

    <Button
        android:id="@+id/bt_selectDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择日期"
        />

</LinearLayout>
posted @ 2024-03-19 18:07  aallofitisst  阅读(7)  评论(0)    收藏  举报