ภาพรวม
บทความนี้สาธิตวิธีตรวจสอบการหมุนหน้าจอ (Orientation) ว่าอยู่ในโหมด Portrait (แนวตั้ง) หรือ Landscape (แนวนอน) โดยใช้ onConfigurationChanged()
ขั้นตอนที่ 1: สร้างโปรเจกต์
Android Studio → File → New Project → Empty Activity
ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/conf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)
package com.example.myapplication;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView confTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confTextView = findViewById(R.id.conf);
updateOrientationText();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
updateOrientationText();
}
private void updateOrientationText() {
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
confTextView.setText("อยู่ในโหมด Landscape (แนวนอน)");
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
confTextView.setText("อยู่ในโหมด Portrait (แนวตั้ง)");
} else {
confTextView.setText("ไม่ทราบโหมด");
}
}
}
ขั้นตอนที่ 4: AndroidManifest.xml - สำคัญมาก
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
...>
...
</activity>
ต้องเพิ่ม android:configChanges มิฉะนั้น Activity จะถูกสร้างใหม่ (recreate) ทุกครั้งที่หมุนหน้าจอ และ onConfigurationChanged จะไม่ถูกเรียก
คำอธิบาย configChanges
orientation- การหมุนหน้าจอscreenSize- ขนาดหน้าจอเปลี่ยน (จำเป็นสำหรับ API 13+)screenLayout- การจัดวางหน้าจอเปลี่ยนkeyboardHidden- แป้นพิมพ์ซ่อน/แสดง
วิธีอื่น: ใช้ ViewTreeObserver (ไม่ต้อง configChanges)
View rootView = findViewById(android.R.id.content);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
int width = rootView.getWidth();
int height = rootView.getHeight();
boolean isPortrait = height > width;
// อัปเดต UI ตาม isPortrait
});
ทดสอบ
หมุนอุปกรณ์ ข้อความจะเปลี่ยนระหว่าง "Portrait" และ "Landscape" โดย Activity ไม่ restart