美文网首页Android 成长笔记
Android TimePicker 使用示例

Android TimePicker 使用示例

作者: 赵者也 | 来源:发表于2017-03-25 12:19 被阅读180次

    布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorGray"
        android:orientation="vertical"
        >
    
        <TimePicker
            android:id="@+id/timePicker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    
        <TextView
            android:id="@+id/showText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            />
    
    </LinearLayout>
    

    主程序代码:

    package com.toby.personal.testlistview;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.widget.DatePicker;
    import android.widget.TextView;
    import android.widget.TimePicker;
    
    import java.util.Calendar;
    
    public class MainActivity extends AppCompatActivity {
    
        final private static String TAG = "Toby_Test";
    
        private int year;
        private int month;
        private int day;
        private int hour;
        private int minute;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            month = c.get(Calendar.MONTH);
            day = c.get(Calendar.DATE);
            hour = c.get(Calendar.HOUR);
            minute = c.get(Calendar.MINUTE);
    
            final TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
            timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
                @Override
                public void onTimeChanged(TimePicker timePicker, int h, int m) {
                    hour = h;
                    minute = m;
                    showDate(year, month, day, h, m);
                }
            });
    
            showDate(year, month, day, hour, minute);
        }
    
        private void showDate(int y, int M, int d, int h, int m) {
            TextView showText = (TextView) findViewById(R.id.showText);
            showText.setText("Current Datetime: " + y + "/" + (M + 1) + "/" + d + " " + h + ":" + m);
        }
    
    }
    

    运行效果:


    使用示例

    参考文献:《疯狂Android讲义(第2版)》

    相关文章

      网友评论

        本文标题:Android TimePicker 使用示例

        本文链接:https://www.haomeiwen.com/subject/vbccottx.html