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

Khóa hướng màn hình (Orientation) lập trình trong Android

Khóa hướng màn hình (Orientation) lập trình trong Android

Hướng dẫn này minh họa cách khóa hướng màn hình (giữ portrait hoặc landscape) bằng code tại runtime.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (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"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Screen Orientation Lock"
        android:textSize="24sp"
        android:textStyle="bold"/>
</RelativeLayout>

Bước 3: Code MainActivity.java

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Lấy hướng hiện tại
        int currentOrientation = getResources().getConfiguration().orientation;
        
        // Khóa tại hướng hiện tại
        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, chạy app. Màn hình sẽ bị khóa tại hướng hiện tại (dọc hoặc ngang) ngay khi activity tạo. Xoay thiết bị sẽ không thay đổi giao diện.

Các hằng số SCREEN_ORIENTATION quan trọng:
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT        // Khóa dọc
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE       // Khóa ngang
ActivityInfo.SCREEN_ORIENTATION_SENSOR          // Tự động theo cảm biến
ActivityInfo.SCREEN_ORIENTATION_USER            // Theo cài đặt user (auto-rotate on/off)
ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR     // Tự động, bao gồm upside-down
ActivityInfo.SCREEN_ORIENTATION_LOCKED          // Khóa tại hướng hiện tại (API 18+)
ActivityInfo.SCREEN_ORIENTATION_BEHIND          // Theo activity phía sau

Các cách khóa hướng màn hình

Cách 1: Trong Manifest (Khóa cố định cho toàn activity)

<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait" > <!-- hoặc landscape -->
</activity>

Cách 2: Trong Code (Linh hoạt, có thể thay đổi runtime)

// Khóa portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

// Khóa landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

// Mở khóa (tự động xoay)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

// Khóa tại hướng hiện tại (API 18+)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);

Cách 3: Khóa portrait nhưng cho phép landscape trên tablet

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // Kiểm tra kích thước màn hình
    boolean isTablet = (getResources().getConfiguration().screenLayout 
        & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    
    if (!isTablet) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    // Tablet: cho phép xoay tự do
}
Lưu ý:
  • Gọi setRequestedOrientation() trước setContentView() để tránh nháy màn hình
  • Việc khóa hướng có thể gây trải nghiệm xấu trên tablet/foldable
  • Android 12+ khuyến khích hỗ trợ multi-window và tự do xoay
  • Game/video thường khóa landscape, app đọc tin khóa portrait