Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีดึงเวลาท้องถิ่นใน Android ด้วยคลาส LocalTime API

ตัวอย่างนี้สาธิตวิธีการดึงเวลาท้องถิ่น (Local Time) ใน Android โดยใช้คลาส LocalTime API

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: ออกแบบหน้าจอ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Local Date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ในโค้ดด้านบน เราใช้ TextView เพื่อแสดงเวลา

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.LocalTime;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.date);

        // LocalTime ต้องการ API Level 26 (Android 8.0 Oreo) ขึ้นไป
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            LocalTime time = LocalTime.now();
            textView.setText("Time " + time.toString());
        }
    }
}

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีดึงเวลาท้องถิ่นใน Android ด้วยคลาส LocalTime API

ผลลัพธ์จะแสดงเวลาปัจจุบันพร้อมวินาที