android控件開發之TimerPicker和DatePicker
java代碼:
package com.example.timepicker;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
public class MainActivity extends Activity {
private final int TIMER = 1;
private final int DATE = 2;
private Button showTimerButton = null;
private Button showDateButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showTimerButton = (Button)findViewById(R.id.showTimePicker);
showTimerButton.setOnClickListener(new showTimerDialogListener());
showDateButton = (Button)findViewById(R.id.showDatePicker);
showDateButton.setOnClickListener(new showDateDialogListener());
}
//Date button的監聽器
class showDateDialogListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//顯示Date Diaolog
showDialog(DATE);
}
}
//Timer button 監聽器
class showTimerDialogListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//顯示ID為TIMER的dialog
showDialog(TIMER);
//TimePickerDialog timerDialog = new TimePickerDialog(this, onTimeSetListener, 22, 54, true);
//timerDialog.show();
}
}
//此方法由showDialog()調用並且傳入Dialog ID
protected Dialog onCreateDialog(int id){
Dialog dialog = null;
switch(id){
//當ID為TIMER時,創建一個TimePickerDialog對象並且返回
case TIMER:
dialog = new TimePickerDialog(this, onTimeSetListener, 22, 54, true);
break;
//當ID為DATE時,創建一個DatePickerDialog對象並且返回
case DATE:
dialog = new DatePickerDialog(this, onDateSetListener, 2014, 12, 10);
break;
}
return dialog;
}
main.xml文件如下:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
android:id="@+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
Strings.xml代碼如下:
PickerDialog
Settings
Hello world!
Show Time Dialog
Show Date Dialog
顯示效果如下:
主界面:
點擊Show Timer Dialog 按鈕出現如下:
點擊Show Date Dialog出現如下: