时间选择器,选择日期DatePicker

作者:华清远见讲师

时间选择器,选择日期DatePicker

效果图

布局比较简单,直接从看代码:

import java.util.Calendar;

import android.app.Activity;

import android.app.DatePickerDialog;

import android.app.Dialog;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.DatePicker;

import android.widget.TextView;

/**

* 时间选择器

*/

public class MainActivity extends Activity {

int mYear, mMonth, mDay;

Button btn;

TextView dateDisplay;

final int DATE_DIALOG = 1;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btn = (Button) findViewById(R.id.dateChoose);

dateDisplay = (TextView) findViewById(R.id.dateDisplay);

btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

showDialog(DATE_DIALOG);

}

});

final Calendar ca = Calendar.getInstance();

mYear = ca.get(Calendar.YEAR);

mMonth = ca.get(Calendar.MONTH);

mDay = ca.get(Calendar.DAY_OF_MONTH);

}

@Override

protected Dialog onCreateDialog(int id) {

switch (id) {

case DATE_DIALOG:

return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);

}

return null;

}

/**

* 设置日期利用StringBuffer追加

*/

public void display() {

dateDisplay.setText(new StringBuffer().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));

}

private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

@Override

public void onDateSet(DatePicker view, int year, int monthOfYear,

int dayOfMonth) {

mYear = year;

mMonth = monthOfYear;

mDay = dayOfMonth;

display();

}

};

}

xml布局文件代码如下:

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:gravity="center"

android:orientation="vertical">

android:id="@+id/dateDisplay"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="我是默认时间显示"/>

android:id="@+id/dateChoose"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="选择日期" />

展开阅读全文

没有更多推荐了,返回首页