DatePick

MainActivity.java

package com.example.datepicktest;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;

/*实现 日期选择器的实例,以及点击触发事件,*/
public class MainActivity extends Activity {
    private Button mBtn_datepick;
    private static final int DATE_PICKER_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtn_datepick = (Button) findViewById(R.id.btn_datepick);
        mBtn_datepick.setOnClickListener(new BtnListener());

    }

    private class BtnListener implements OnClickListener{

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
// 此方法执行后会回调oncreateDialog方法,通过输入的ID进行标识,
            showDialog(DATE_PICKER_ID);

        }

    }

// 匿名内部类,onDAtesetListenner是个接口,
    DatePickerDialog.OnDateSetListener OnDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            System.out.println(year + "-" + monthOfYear + "-" + dayOfMonth);

        }
    };

// 重写的oncreateDialog方法
    protected android.app.Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_PICKER_ID:
            return new DatePickerDialog(MainActivity.this, OnDateSetListener, 2015, 11, 25);

        default:
            break;
        }
        return null;

    };

}

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

    <Button android:id="@+id/btn_datepick" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/btn_datepick"/>

</LinearLayout>   

你可能感兴趣的:(DatePick)