日期/时间选择对话框(DatePickerDialog和TimePickerDialog)的使用
<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" >
<EditText
android:id="@+id/edit"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="日期选择器" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="时间选择器" />
</LinearLayout>
public class MainActivity extends Activity {
private Button dateButton;
private Button timeButton;
private EditText editText;
private DatePickerDialog dateDialog;
private TimePickerDialog timeDialog;
private int year, monthOfYear, dayOfMonth, hourOfDay, minute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dateButton = (Button) findViewById(R.id.button1);
timeButton = (Button) findViewById(R.id.button2);
editText = (EditText) findViewById(R.id.edit);
Calendar calendar = Calendar.getInstance();
year = calendar.get(calendar.YEAR);
monthOfYear = calendar.get(calendar.MONTH);
dayOfMonth = calendar.get(calendar.DAY_OF_MONTH);
hourOfDay = calendar.get(calendar.HOUR_OF_DAY);
minute = calendar.get(calendar.MINUTE);
dateDialog = new DatePickerDialog(this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int year, int monthOfYear,
int dayOfMonth) {
String text = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
editText.setText(text);
}
}, year, monthOfYear, dayOfMonth);
dateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dateDialog.show();
}
});
timeDialog = new TimePickerDialog(this, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(MainActivity.this, hourOfDay + ":" + minute,
Toast.LENGTH_LONG).show();
}
}, hourOfDay, minute, true);
timeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
timeDialog.show();
}
});
}
}
|