第一步:在MainActivity的代码:
package com.example.yangjian.learncomponents; import android.app.DatePickerDialog; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; public class chooseADate extends ActionBarActivity { private Button btnChooseDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_adate); btnChooseDate = (Button) findViewById(R.id.btnChooseDate); btnChooseDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DatePickerDialog(chooseADate.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { String thedate = String.format("%d-%d-%d", monthOfYear+1, dayOfMonth); System.out.println(thedate); btnChooseDate.setText(thedate); } },2015,8,3).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_choose_adate, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
第二步:在xml文件中的代码:
<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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.yangjian.learncomponents.chooseADate"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0000-00-00" android:id="@+id/btnChooseDate"/> </LinearLayout>