Android 控件之DatePicker(日期和日历)

Android 控件之DatePicker(日期和日历)

在xml文件中添加DatePicker控件,自动生成的文件代码不用修改。

接下来实现时间初始化,以及修改时间事件监听,用Toast显示出来:

package com.example.time;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.DatePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
	private DatePicker datePicker;
	private int year, monthOfYear, dayOfMonth;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		datePicker = (DatePicker) this.findViewById(R.id.datePicker1);
		// 获得系统日期 初始化年月日
		Calendar calendar = Calendar.getInstance();
		year = calendar.get(calendar.YEAR);
		monthOfYear = calendar.get(calendar.MONTH);
		dayOfMonth = calendar.get(calendar.DAY_OF_MONTH);

		datePicker.init(year, monthOfYear, dayOfMonth,// 匿名内部类
				new DatePicker.OnDateChangedListener() {

					@Override
					public void onDateChanged(DatePicker arg0, int year,
							int monthOfYear, int dayOfMonth) {
						// TODO Auto-generated method stub
						String value = year + "年" + (monthOfYear + 1) + "月"
								+ dayOfMonth + "日";
						Toast.makeText(MainActivity.this, value, 1).show();
						// 月份+1
					}
				});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
打开即可以显示系统时间,修改后会以Toast形式显:

Android 控件之DatePicker(日期和日历)_第1张图片


   

你可能感兴趣的:(Android开发笔记)