ภาพรวม
ตัวอย่างนี้สาธิตการสร้างตัวเลขสุ่ม (Random Number) ในช่วงที่ผู้ใช้กำหนด (Min - Max) โดยใช้ java.util.Random และ Kotlin Standard Library
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project
ขั้นตอนที่ 2: Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Random Number Generator"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="@+id/editTextMin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/text"
android:layout_marginTop="30dp"
android:ems="10"
android:hint="Minimum Value"
android:inputType="number" />
<EditText
android:id="@+id/editTextMax"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMin"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Maximum Value"
android:inputType="number" />
<Button
android:id="@+id/btn_generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMax"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="GENERATE" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_generate"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text=""
android:textColor="@android:color/black"
android:textSize="36sp"
android:textStyle="bold" />
</RelativeLayout>
ขั้นตอนที่ 3: MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random
class MainActivity : AppCompatActivity() {
private lateinit var editTextMin: EditText
private lateinit var editTextMax: EditText
private lateinit var button: Button
private lateinit var textViewResult: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
editTextMin = findViewById(R.id.editTextMin)
editTextMax = findViewById(R.id.editTextMax)
button = findViewById(R.id.btn_generate)
textViewResult = findViewById(R.id.textViewResult)
button.setOnClickListener {
val minStr = editTextMin.text.toString().trim()
val maxStr = editTextMax.text.toString().trim()
if (minStr.isEmpty() || maxStr.isEmpty()) {
Toast.makeText(this, "Please enter both values", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val min = minStr.toIntOrNull()
val max = maxStr.toIntOrNull()
if (min == null || max == null) {
Toast.makeText(this, "Invalid numbers", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
if (min > max) {
Toast.makeText(this, "Min cannot be greater than Max", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// วิธีที่ 1: ใช้ Kotlin Random (API 1.3+)
val randomNumber = Random.nextInt(min, max + 1) // max inclusive
// วิธีที่ 2: ใช้ Java Random (เก่า)
// val random = java.util.Random()
// val randomNumber = random.nextInt(max - min + 1) + min
textViewResult.text = randomNumber.toString()
}
}
}
วิธีสุ่มตัวเลขใน Kotlin (สรุป)
| วิธี | Syntax | ช่วง | หมายเหตุ |
|---|---|---|---|
| Kotlin Random | Random.nextInt(min, max) | [min, max) ไม่รวม max | แนะนำ ใช้ Kotlin 1.3+ |
| Kotlin Range | (min..max).random() | [min, max] รวม max | สั้นกระชับ |
| Java Random | Random().nextInt(max-min+1)+min | [min, max] รวม max | รุ่นเก่า |
| ThreadLocalRandom | ThreadLocalRandom.current().nextInt(min, max+1) | [min, max] รวม max | Thread-safe, ประสิทธิภาพดี |
| SecureRandom | SecureRandom().nextInt(max-min+1)+min | [min, max] รวม max | สำหรับ Cryptography |
ตัวอย่างเพิ่มเติม
// สุ่ม Double
val randomDouble = Random.nextDouble(0.0, 1.0)
// สุ่ม Boolean
val randomBool = Random.nextBoolean()
// สุ่มจาก List
val list = listOf("Apple", "Banana", "Cherry")
val randomItem = list.random()
// สุ่มหลายค่าไม่ซ้ำ (Shuffle)
val numbers = (1..49).toList().shuffled().take(6) // สลากกินแบ่ง 6 ตัว
// สุ่มด้วย Seed (Reproducible)
val seededRandom = Random(12345L)
val predictable = seededRandom.nextInt(1, 100)
ขั้นตอนที่ 4: Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.randomnumber">
<application ... >
<activity android:name=".MainActivity"> ... </activity>
</application>
</manifest>
การทดสอบ
รันแอป กรอก Minimum = 1, Maximum = 100 กด GENERATE จะได้ตัวเลขสุ่มระหว่าง 1-100