package dateandtimer;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import com.example.ctroltest.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerTest extends Activity {
private TextView datedisp;
private Button dateselectbtn;
private int myear,mmonth,mday;
private DatePickerDialog.OnDateSetListener dateListener=new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
datedisp.setText("你選擇了"+year+"年"+(monthOfYear+1) +"月"+dayOfMonth+"日");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.date_picker_test);
datedisp=(TextView)findViewById(R.id.datedisp);
dateselectbtn=(Button)findViewById(R.id.dateselectbtn);
Calendar myCalendar=Calendar.getInstance(Locale.CHINA);
Date mydate=new Date();
myCalendar.setTime(mydate);
myear=myCalendar.get(Calendar.YEAR);
mmonth=myCalendar.get(Calendar.MONTH);
mday=myCalendar.get(Calendar.DAY_OF_MONTH);
dateselectbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DatePickerDialog datePickerDialog=
new DatePickerDialog(DatePickerTest.this,dateListener, myear,mmonth, mday);
datePickerDialog.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.date_picker_test, menu);
return true;
}
}
布局檔案:
<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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="日期為:" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/datedisp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="選擇日期"
android:id="@+id/dateselectbtn"
/>
</LinearLayout>
</LinearLayout>
最後的效果: