手机设置时间日期很普遍,今天就梳理下。
首先在拖入一个按钮 ,日期和时间控件到工程里,如图:
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <DatePicker 8 android:id="@+id/today" 9 android:layout_width="wrap_content" 10 android:layout_height="182dp" /> 11 12 <TimePicker 13 android:id="@+id/now" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" /> 16 17 <Button 18 android:id="@+id/button1" 19 android:layout_width="wrap_content" 20 android:layout_height="wrap_content" 21 android:text="保存" /> 22 23 </LinearLayout>
然后修改MainActivity.java文件:如下
1 package com.example.datetimedemo; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.Menu; 6 import android.view.MenuItem; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.Button; 10 import android.widget.DatePicker; 11 import android.widget.TimePicker; 12 import android.widget.Toast; 13 14 public class MainActivity extends Activity { 15 16 private DatePicker dpToday=null; 17 private TimePicker tpNow=null; 18 private Button btnSave=null; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 24 dpToday = (DatePicker)findViewById(R.id.today); 25 tpNow = (TimePicker)findViewById(R.id.now); 26 btnSave = (Button)findViewById(R.id.button1); 27 btnSave.setOnClickListener(new SaveClick()); 28 } 29 30 public class SaveClick implements OnClickListener{ 31 32 @Override 33 public void onClick(View v) { 34 int iYear=0; 35 int iMonth=0; 36 int iDay=0; 37 String sDate=""; 38 iYear = dpToday.getYear(); 39 iMonth = dpToday.getMonth() + 1; //返回月份从0到11,故要加1 40 iDay = dpToday.getDayOfMonth(); 41 42 43 sDate="日期: " + String.valueOf(iYear) + "年" + String.valueOf(iMonth) + "月" 44 + String.valueOf(iDay) + "日"; 45 46 int iHour=0; 47 int iMin=0; 48 String sTime=""; 49 iHour=tpNow.getCurrentHour(); 50 iMin=tpNow.getCurrentMinute(); 51 sTime="时间:"+String.valueOf(iHour)+"时"+String.valueOf(iMin)+"分"; 52 53 Toast.makeText(getApplicationContext(), sDate+sTime, Toast.LENGTH_LONG).show(); 54 55 } 56 57 } 58 59 @Override 60 public boolean onCreateOptionsMenu(Menu menu) { 61 // Inflate the menu; this adds items to the action bar if it is present. 62 getMenuInflater().inflate(R.menu.main, menu); 63 return true; 64 } 65 66 @Override 67 public boolean onOptionsItemSelected(MenuItem item) { 68 // Handle action bar item clicks here. The action bar will 69 // automatically handle clicks on the Home/Up button, so long 70 // as you specify a parent activity in AndroidManifest.xml. 71 int id = item.getItemId(); 72 if (id == R.id.action_settings) { 73 return true; 74 } 75 return super.onOptionsItemSelected(item); 76 } 77 }
显示效果如下: