Giới thiệu
Hướng dẫn này trình bày cách khóa hướng màn hình (chỉ portrait hoặc chỉ landscape) trong ứng dụng Android, vừa qua code Java vừa qua Manifest.
Các bước thực hiện
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 (res/layout/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:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity"
android:background="#ecdcf1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Chế độ dọc (portrait) đã bị khóa!"
android:textStyle="bold"
android:textColor="@color/colorPrimary"
android:layout_centerVertical="true"/>
</RelativeLayout>
Bước 3: Viết logic xử lý (src/MainActivity.java)
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Khóa ở chế độ ngang (landscape) qua code
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
}
}
Bước 4: Cấu hình Manifest (androidManifest.xml) - Cách thay thế
<?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"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Hai cách khóa hướng màn hình
Cách 1: Trong Manifest (khuyến nghị)
Thêm thuộc tính android:screenOrientation vào thẻ <activity>:
portrait- Chỉ dọclandscape- Chỉ ngangsensor- Theo cảm biếnuser- Theo cài đặt người dùng
Cách 2: Trong Code Java
Gọi setRequestedOrientation() trong onCreate() trước setContentView():
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Lưu ý
- Cách Manifest hiệu quả hơn, áp dụng ngay từ khi Activity khởi tạo
- Cách code cho phép thay đổi động theo điều kiện
- Nếu dùng cả hai, Manifest có ưu tiên cao hơn
Chạy ứng dụng
Kết nối thiết bị Android, nhấn Run trong Android Studio. Màn hình sẽ bị khóa ở chế độ landscape (qua code) hoặc portrait (qua Manifest).
