ปกติแล้วเวลาที่เราพลิกหน้าจอของมือถือให้อยู่ในแนวตั้งหรือแนวนอน โปรแกรมที่เราสร้างขึ้นมาก็จะพลิกตามไปด้วย แต่หากบางทีเราไมได้ต้องการให้มันพลิกตามไปกับหน้าจอด้วยจะทำยังไงดี การเขียนโปรแกรมบนแอนดรอยด์สามารถกำหนดได้ว่าจะให้แสดงในแนวตั้งหรือแนวนอนได้ง่ายๆ ด้วยการเพิ่ม android:screenOrientation=”landscape” หรือ android:screenOrientation=”portrait” เข้าไปใน AndroidManifest.xml ง่ายมักๆ
ลองดูตัวอย่างสักตัวอย่างดีกว่า เริ่มด้วยการสร้างแอนดรอยด์โปรเจคขึ้นมาใหม่สักอันหนึ่งก่อน
ทำการเปิด AndroidManifest.xml และเพิ่ม android:screenOrientation=”landscape” เข้าไปในส่วนของ activity
จะได้ AndroidManifest.xml ออกมาหน้าตาประมาณนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.LookHin.EasyScreenOrientation" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".EasyScreenOrientation" android:label="@string/app_name" android:screenOrientation="landscape"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="8" /> </manifest> |
ในตัวอย่างนี้เราจะแสดงรูป Wall-E กับ Eve โดยให้ทำการสร้างโฟล์เดอร์ drawable เอาไว้ใน res และทำการ copy รูปไปไว้ในนั้น
# wall_e_icon.png
# eve_icon.png
ต่อไปทำการแก้ไข res -> layout -> main.xml โดยให้เพิ่ม ImageView เพื่อที่จะใช้แสดงรูปสองรูป
# main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/ImageView01" android:src="@drawable/wall_e_icon" android:layout_height="wrap_content" android:layout_width="fill_parent"> </ImageView> <ImageView android:id="@+id/ImageView02" android:layout_height="wrap_content" android:src="@drawable/eve_icon" android:layout_width="fill_parent"> </ImageView> </LinearLayout> |
เรียบร้อยแล้วทดสอบโปรแกรมได้
# android:screenOrientation=”landscape”
# android:screenOrientation=”portrait”
Download Source Code ทั้งหมดได้จาก https://www.unzeen.com/download/android/EasyScreenOrientation.zip