Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Vô hiệu hóa chế độ Landscape (ngang) trong Android

Mục tiêu

Buộc ứng dụng chỉ chạy ở chế độ Portrait (dọc), không cho xoay ngang.

Cách làm: Khai báo trong AndroidManifest.xml

Bước 1: Tạo project

Bước 2: Layout activity_main.xml (bình thường)

<LinearLayout ...>
    <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" />
</LinearLayout>

Bước 3: AndroidManifest.xml - Thêm screenOrientation

<manifest ... package="com.example.andy.myapplication">
    <application ...>
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait">  <!-- Quan trọng -->
            <intent-filter>...</intent-filter>
        </activity>
    </application>
</manifest>

Thêm android:screenOrientation="portrait" vào thẻ <activity>. Activity này sẽ chỉ hiển thị dọc.

Lưu ý: Nếu thêm vào thẻ <application> thì áp dụng cho toàn bộ app.

Kết quả

Trước khi set: hỗ trợ cả 2 chế độ (ảnh minh họa landscape & portrait).

Sau khi set: Chỉ hiển thị portrait, xoay thiết bị không thay đổi giao diện:

Vô hiệu hóa chế độ Landscape (ngang) trong Android

Giá trị khác của screenOrientation

  • landscape: Chỉ ngang.
  • sensor: Theo cảm biến (mặc định).
  • nosensor: Bỏ qua cảm biến, giữ orientation hiện tại.
  • userPortrait, userLandscape: Theo cài đặt user.
  • fullSensor: Cho phép 4 hướng (API 9+).