Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

프로그래밍 방식으로 안드로이드 내비게이션 바의 높이와 너비 구하는 방법

이 글에서는 프로그래밍 방식으로 안드로이드 내비게이션 바(하단 탐색 모음)의 높이와 너비 값을 가져오는 방법을 단계별로 살펴봅니다. 내비게이션 바의 크기는 기기 제조사와 해상도에 따라 달라지기 때문에, UI 요소를 정교하게 배치해야 할 때 이 값을 동적으로 조회하면 매우 유용합니다.

1단계 — 새 프로젝트 만들기

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성하고, 필요한 정보를 모두 입력합니다.

2단계 — 레이아웃 작성(activity_main.xml)

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="Android Navigation Bar Height and Width"
    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>

3단계 — MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. getIdentifier() 메서드로 시스템 차원(dimen) 리소스인 navigation_bar_heightnavigation_bar_width의 리소스 ID를 찾은 후, getDimensionPixelSize()를 사용해 실제 픽셀 값을 구해 화면에 표시합니다.

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();

        int heightId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int widthId = resources.getIdentifier("navigation_bar_width", "dimen", "android");

        if (heightId > 0 && widthId > 0) {
            int heightPx = resources.getDimensionPixelSize(heightId);
            int widthPx = resources.getDimensionPixelSize(widthId);
            textView.setText(heightPx + " x " + widthPx + " px");
        }
    }
}

참고: 일부 기기나 Android 버전에서는 navigation_bar_width 값이 존재하지 않을 수 있습니다. 이 경우 getIdentifier()가 0을 반환하므로, 해당 값이 없을 때는 높이만 표시하도록 분기 처리하는 것이 안전합니다.

4단계 — AndroidManifest.xml 설정

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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 프로그래밍 방식으로 안드로이드 내비게이션 바의 높이와 너비 구하는 방법 실행 아이콘을 클릭합니다. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 내비게이션 바의 높이와 너비가 픽셀(px) 단위로 표시되는 것을 확인할 수 있습니다.

프로그래밍 방식으로 안드로이드 내비게이션 바의 높이와 너비 구하는 방법