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

Lấy chiều cao và rộng Navigation Bar Android theo chương trình

Giới thiệu

Bài viết này hướng dẫn cách lấy kích thước (chiều cao, chiều rộng) của Navigation Bar ảo (navigation bar) trên Android theo chương trình. Điều này hữu ích khi thiết kế giao diện fullscreen, tính toán vùng hiển thị thực tế, hoặc xử lý layout tránh bị che bởi navigation bar.

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"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chiều cao và rộng Navigation Bar Android"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textStyle="bold" />

</LinearLayout>

Bước 3: Viết code lấy kích thước (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.textView);
        Resources resources = getApplicationContext().getResources();

        // Lấy resource ID của navigation_bar_height
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        
        if (resourceId > 0) {
            // Lấy giá trị pixel thực tế
            int navBarHeight = resources.getDimensionPixelSize(resourceId);
            
            // Lấy navigation_bar_width (nếu có, thường cho landscape)
            int widthResourceId = resources.getIdentifier("navigation_bar_width", "dimen", "android");
            int navBarWidth = 0;
            if (widthResourceId > 0) {
                navBarWidth = resources.getDimensionPixelSize(widthResourceId);
            }
            
            textView.setText("Navigation Bar Height: " + navBarHeight + "px\n" +
                           "Navigation Bar Width: " + navBarWidth + "px");
        } else {
            textView.setText("Thiết bị không có Navigation Bar ảo hoặc không tìm thấy resource");
        }
    }
}

Bước 4: Cấu hình Manifest (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>
                
                
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run, chọn thiết bị. Kết quả hiển thị chiều cao/rộng navigation bar tính bằng pixel.

Giải thích chi tiết

  • getIdentifier("navigation_bar_height", "dimen", "android"): Tìm resource ID của dimension hệ thống tên là "navigation_bar_height" trong package "android".
  • getDimensionPixelSize(resourceId): Lấy giá trị pixel thực tế (đã scale theo density) từ resource ID.
  • Trả về 0 nếu thiết bị dùng nút cứng (hardware keys) hoặc gesture navigation không có navigation bar ảo.

Các resource dimension liên quan

Resource Name Mô tả
navigation_bar_height Chiều cao navigation bar (portrait)
navigation_bar_width Chiều rộng navigation bar (landscape)
status_bar_height Chiều cao status bar
navigation_bar_height_landscape Chiều cao nav bar ở landscape (một số thiết bị)

Cách xử lý an toàn hơn (API 30+)

// Cách hiện đại hơn dùng WindowInsets (API 30+)
ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, insets) -> {
    Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
    Insets navBars = insets.getInsets(WindowInsetsCompat.Type.navigationBars());
    
    int navBarHeight = navBars.bottom;
    int navBarWidth = navBars.right; // landscape
    
    // Cập nhật UI...
    return insets;
});

Lưu ý quan trọng

  • Navigation bar có thể thay đổi kích thước khi xoay màn hình hoặc bật/tắt gesture navigation.
  • Nên lắng nghe thay đổi qua WindowInsetsAnimation.Callback hoặc OnApplyWindowInsetsListener để cập nhật layout động.
  • Trên một số OEM (Samsung, Xiaomi...), tên resource có thể khác, cần fallback.