android 之日期选择器,Android GUI 之日期选择器(DatePicker)

简单介绍下 DatePicker 和 Calender ,用他们两个实现日期选择器,并添加日期改变监听器

0818b9ca8b590ca3270a3433284dd417.png

将当前时间显示在下面的 TextView 上,日期改变时 TextView 上的日期相应改变

代码:

package com.th;

import java.util.Calendar;

import android.app.Activity;

import android.os.Bundle;

import android.widget.DatePicker;

import android.widget.DatePicker.OnDateChangedListener;

import android.widget.TextView;

public class MainActivity extends Activity {

private DatePicker datepicker;

private TextView textview;

Calendar calendar;

int cur_year, cur_month, cur_day;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//获取布局文件中的两个组件

datepicker = (DatePicker)findViewById(R.id.datePicker1);

textview = (TextView)findViewById(R.id.textView1);

calendar = Calendar.getInstance();//生成 Calendar 对象

cur_year = calendar.get(Calendar.YEAR);//获取当前日期

cur_month = calendar.get(Calendar.MONTH);

cur_day = calendar.get(Calendar.DAY_OF_MONTH);

//显示当前的日期,月要加 1

textview.setText("当前时间:" +

cur_year + "年" + (cur_month + 1) + "月" + cur_day + "日");

//注册日期改变监听器

datepicker.init(cur_year, cur_month, cur_day, new MyDateChangedListener());

}

/* MyDateChangedListener 类实现日期改变监听器的功能,当日期改变时,

onDateChanged 方法被调用更新日期*/

private class MyDateChangedListener implements OnDateChangedListener {

/* onDateChanged 方法中各个参数的含义:

* @param view 当前发生变化的时间选择器

* @param year 当前时间选择器的年

* @param monthOfYear 当前时间选择器的月 返回值为(0 ~ 11)故使用时要加 1

* @param dayOfMonth 当前时间选择器的日

* */

@Override

public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

cur_year = year;

cur_month = monthOfYear + 1;

cur_day = dayOfMonth;

textview.setText("当前时间:" +

cur_year + "年" + cur_month + "月" + cur_day + "日");

}

}

}

布局文件:

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

android:id="@+id/datePicker1"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="TextView" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值