安卓学习-界面-ui-DatePicker和TimePicker

XML属性 方法 说明
android:calendarViewShown  setCalendarViewShown(boolean shown)

是否显示日历,默认显示,设置为false,就没

右边那个东西了

android:spinnersShown setSpinnersShown(boolean shown)

设置为false,左边那个年、月就没了

android:endYear   设置允许选的最后一年,相当于最大的年
android:startYear   设置允许选的第一年,相当于最小年
android:maxDate

 setMaxDate(long maxDate)

Calendar c=Calendar.getInstance();
c.set(Calendar.YEAR, 2014);
//11相当于12月
c.set(Calendar.MONTH, 11);
DatePicker d=(DatePicker)findViewById(R.id.datePicker1);
d.setMaxDate(c.getTimeInMillis());

 

允许选择的最小日期,格式MM/DD/YYYY
android:minDate  setMinDate(long minDate) 允许选择的最大日期,格式MM/DD/YYYY

例子

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <DatePicker
        android:id="@+id/datePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:calendarViewShown="false"
         />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
View Code

MainActivity.java

public class MainActivity extends Activity {

    DatePicker d;    
    TimePicker t;
    TextView textView1;
    TextView textView2;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        d=(DatePicker)findViewById(R.id.datePicker1);
        t=(TimePicker)findViewById(R.id.timePicker1);    
        textView1=(TextView)findViewById(R.id.textView1);
        textView2=(TextView)findViewById(R.id.textView2);
        
        Calendar c=Calendar.getInstance();
        d.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), new OnDateChangedListener() {
            public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                textView1.setText(year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"年");
            }
        });
        
        t.setOnTimeChangedListener(new OnTimeChangedListener() {
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                textView2.setText(hourOfDay+"点"+minute+"分");
            }
        });
    }
}
View Code

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。