Android---29---DatePicker、TimePick
DatePicker与TimePicker是用来显示时间的控件。
onDateChanged、 onTimeChanged分别是控件的触发事件。
MainActivity.java:
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.DatePicker; import android.widget.TextView; import android.widget.DatePicker.OnDateChangedListener; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; import android.widget.Toast; /** * 时间控件的使用 * * @author Caesar * */ public class MainActivity extends Activity implements OnDateChangedListener, OnTimeChangedListener { private TextView textView; private DatePicker datePicker; private TimePicker timePicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); datePicker = (DatePicker) findViewById(R.id.datepicker); textView = (TextView) findViewById(R.id.textview); timePicker = (TimePicker) findViewById(R.id.timepicker); datePicker.init(2015, 4, 24, this);// 初始化日期 timePicker.setIs24HourView(true);// 显示时间是否按照24小时制 timePicker.setOnTimeChangedListener(this);// 注册事件 } // 时间控件的触发 @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "hourOfDay" + hourOfDay + "minute" + minute, 1).show(); } // 日期控件的触发 @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub Calendar calendar = Calendar.getInstance(); calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute()); SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); textView.setText(format.format(calendar.getTime())); } }
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" 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="com.example.datepickerdemo.MainActivity" > <DatePicker android:id="@+id/datepicker" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TimePicker android:id="@+id/timepicker" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18dp" /> </LinearLayout>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。