Android : How to handling Orientation Changed
ปัจจุบันสมาร์ทโฟนสามารถใช้งานได้ทั้งแบบแนวตั้ง (Portrait) และแนวนอน (Landscape) ซึ่งสมาร์ทโฟนมีฟังก์ชันการหมุนหน้าจออัตโนมัติ เพราะฉะนั้นถ้าเราออกแบบแอปปลิเคชันแบบแนวตั้งอย่างเดียว เมื่อผู้ใช้งานหมุนหน้าจอเป็นแนวนอน Layout ของแอปฯก็จะเพี้ยนจนบางครั้งอาจใช้งานไม่ได้ เช่น ปุ่มถูกย่อจนเล็กเกินไป เป็นต้น
วันนี้เราจะมาเรียนรู้วิธีการจัดการ การหมุนหน้าจอของผู้ใช้งานกัน โดย Android ได้เตรียม Call back funtion ให้เรียบร้อย โดยมีขั้นตอนดังนี้
- แก้ไข AndroidManifest.xml สำหรับ Activity ที่เราต้องการ โดยเพิ่มบรรทัดนี้
<activity android:name=".MyActivity" android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" android:label="@string/app_name">
- แก้ไข Java Activity file โดยเพิ่ม Call back function ดังนี้
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Checks the orientation of the screen if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { {... do something when landscape ... } } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ {... do something when portrait ...} } }
จาก call back function เมื่อผู้ใช้หมุนหน้าจอ จะมาเข้าเงื่อนไขดังตัวอย่าง ซึ่งเราก็สามารถกำหนดเงื่อนไขที่แตกต่างกันได้
สมมติว่าถ้าเรามีการออกแบบ Layout สำหรับ Landscape, Portrait แยกกัน เราสามารถเรียกคำส่ัง
setContentView(R.layout.yourlayout_landscape); or setContentView(R.layout.yourlayout_portrait);
ปล. เราสามารถสร้าง layout ชื่อเดียวกันสำหรับ orientation แบบ Portrait, Landscape ได้ โดยการเพิ่ม Project -> New -> android Resource Directory
แล้วเลือก UI MODE >> Landscape แล้วตั้งชื่อ directory ว่า layout-land เมื่อสร้างไดเรกทอรีได้แล้ว เราสามารถสร้าง layout ชื่อเดียวกันได้ โดย layout แบบ landscape จะสร้างไว้ที่ layout-land/yourlayout.xml และ layout แบบ Portrait อยู่ที่ layout/yourlayout.xml