2014-08-03 22:19:21|?次阅读|上传:huigezrx【已有?条评论】发表评论
关键词:Java, Android, 界面设计, 移动应用|来源:唯设编程网
下面是对应Activity类的实现代码:
package com.example.myapplication2.app; import java.text.SimpleDateFormat; import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; public class MainActivity extends Activity { private DatePicker datePicker; private TimePicker timePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_dialog); datePicker = (DatePicker) findViewById(R.id.dpPicker); timePicker = (TimePicker) findViewById(R.id.tpPicker); datePicker.init(2013, 8, 20, new OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // 获取一个日历对象,并初始化为当前选中的时间 Calendar calendar = Calendar.getInstance(); calendar.set(year, monthOfYear, dayOfMonth); SimpleDateFormat format = new SimpleDateFormat( "yyyy年MM月dd日 HH:mm"); Toast.makeText(MainActivity.this, format.format(calendar.getTime()), Toast.LENGTH_SHORT) .show(); } }); timePicker.setIs24HourView(true); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Toast.makeText(MainActivity.this, hourOfDay + "小时" + minute + "分钟", Toast.LENGTH_SHORT).show(); } }); } }
所有代码均在Activity类的onCreate函数中实现,其中调用了DatePicker的init函数对其进行初始化,将默认日期设置为2013年8月20,还实现了日期改变对应的监听器OnDateChangedListener,重载了其onDateChanged函数,当日期改变后,通过Toast的静态方法makeText将对应的日期显示在窗口中。TimePicker类仅仅调用了setIsHourView将其显示方式设置成24小时制,还是先了时间改变对应的接口OnTimeChangedListener,当用户改变时间的时候将对应时间使用Toast的makeText函数显示在面板中。最终实现的效果如下: