ภาพรวม
ตัวอย่างนี้สาธิตวิธีหา ค่ากลาง (middle element) ใน Array บน Android โดยการหารความยาวของอาร์เรย์ด้วย 2
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็น
ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ในโค้ดข้างต้น ใช้ TextView เพื่อแสดงค่ากลางของ Array
ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
// หาตำแหน่งกลาง: length / 2
int middleIndex = array.length / 2;
TextView textView = findViewById(R.id.text);
textView.setText(String.valueOf(array[middleIndex]));
}
}
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอ

Array มี 8 สมาชิก (1-8) ตำแหน่งกลางคือ index 4 (8/2 = 4) ค่าที่ได้คือ 5