效果图如下:
activity_main.xml中的内容如下:
<RelativeLayout 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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/times"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="请选择你要设置的时间" />
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:text="获取到的时间"
/>
</RelativeLayout>
MainActivity的代码如下:
package com.example.datapickers;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainActivity extends Activity implements OnDateSetListener {
private TextView times,tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
times = (TextView) findViewById(R.id.times);
tv = (TextView) findViewById(R.id.tv);
times.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//设置默认时间为现在的时间
new DatePickerDialog(MainActivity.this, MainActivity.this, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get( Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
//
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
tv.setText("获取到的时间为"+year+"-"+(month+1)+"-"+dayOfMonth);
}
}