import java.util.Calendar; import java.util.TimeZone; import android.app.Activity; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; public class TimePickerDialogTest extends Activity { private RelativeLayout mainView=null; private TextView tv=null; private Button button=null; private TimePickerDialog tpd=null; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mainView=new RelativeLayout(this); tv=new TextView(this); RelativeLayout.LayoutParams lp_tv=new RelativeLayout.LayoutParams(-2,-2); lp_tv.addRule(RelativeLayout.CENTER_IN_PARENT); tv.setLayoutParams(lp_tv); tv.setText("请设置时间"); button=new Button(this); RelativeLayout.LayoutParams lp_button=new RelativeLayout.LayoutParams(-2,-2); lp_button.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lp_button.addRule(RelativeLayout.CENTER_HORIZONTAL); button.setLayoutParams(lp_button); button.setText("设置"); button.setOnClickListener(new OnClickListener(){ public void onClick(View v) { if(tpd==null){ tpd_init(); } tpd.show(); } }); mainView.addView(tv); mainView.addView(button); setContentView(mainView); } /*tpd初始化*/ void tpd_init(){ TimePickerDialog.OnTimeSetListener otsl=new TimePickerDialog.OnTimeSetListener(){ public void onTimeSet(TimePicker view, int hourOfDay, int minute) { tv.setText("您设置了时间:"+hourOfDay+"时"+minute+"分"); tpd.dismiss(); } }; Calendar calendar=Calendar.getInstance(TimeZone.getDefault()); int hourOfDay=calendar.get(Calendar.HOUR_OF_DAY); int minute=calendar.get(Calendar.MINUTE); tpd=new TimePickerDialog(this,otsl,hourOfDay,minute,true); } }