鸟语天空
基本视图——DatePicker
post by:追风剑情 2015-9-1 21:37

示例一: 在活动中显示DatePicker

视图


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <Button android:id="@+id/btnSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I am all set!"
        android:onClick="onClick" />
    
    <DatePicker android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


代码


package com.example.androidtest;

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

public class BasicViews4Activity extends Activity {

	DatePicker datePicker;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_basic_views4);
		
		datePicker = (DatePicker) findViewById(R.id.datePicker);
	}
	
	public void onClick(View view)
	{
		Toast.makeText(getBaseContext(), 
				"Date selected:" +(datePicker.getMonth()+1) +
				"/"+datePicker.getDayOfMonth() +
				"/"+datePicker.getYear() + "\n", Toast.LENGTH_SHORT).show();
	}
}


运行效果

11111111111111.png

示例二: 在对话窗口显示DatePicker

代码

package com.example.androidtest;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;

public class BasicViews4Activity extends Activity {

	int yr, month, day;
	static final int DATE_DIALOG_ID = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_basic_views4);
		
		Calendar today = Calendar.getInstance();
		yr = today.get(Calendar.YEAR);
		month = today.get(Calendar.MONDAY);
		day = today.get(Calendar.DAY_OF_MONTH);
		
		showDialog(DATE_DIALOG_ID);
	}
	
	@Override
	protected Dialog onCreateDialog(int id)
	{
		switch(id)
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, yr, month, day);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
	new DatePickerDialog.OnDateSetListener(){
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
		{
			yr = year;
			month = monthOfYear;
			day = dayOfMonth;
			Toast.makeText(getBaseContext(), "You have selected : " + (month+1) +
					"/"+day+"/"+year, Toast.LENGTH_SHORT).show();
		}
	};
}

运行效果

222222222222.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容