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

Cách xác định loại kích thước màn hình Android (small, normal, large, xlarge) bằng code

Giới thiệu

Bài viết này hướng dẫn cách xác định chương trình (programmatically) thiết bị Android thuộc loại kích thước màn hình nào: small, normal, large, xlarge, cũng như mật độ pixel (density: ldpi, mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi).

Các bước thực hiện

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

Khởi tạo project Android Studio mới.

Bước 2: Layout (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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnGetScreenSize"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="getScreenSizeCategory"
        android:text="Lấy Screen Size Category" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnGetScreenSize"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:onClick="getScreenDensity"
        android:text="Lấy Screen Density (DPI)" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Phân loại màn hình: small, normal, large, xlarge"
        android:textAlignment="center"
        android:textSize="18sp"
        android:textStyle="bold|italic" />

</RelativeLayout>

Bước 3: Code Java (src/MainActivity.java)

package app.com.sample;

import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

    // Phân loại kích thước màn hình (Size Category)
    public void getScreenSizeCategory(View view) {
        Configuration config = getResources().getConfiguration();
        int screenLayout = config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;

        String sizeCategory;
        switch (screenLayout) {
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                sizeCategory = "SMALL (Nhỏ)";
                break;
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                sizeCategory = "NORMAL (Trung bình)";
                break;
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
                sizeCategory = "LARGE (Lớn - Tablet 7\")";
                break;
            case Configuration.SCREENLAYOUT_SIZE_XLARGE:
                sizeCategory = "XLARGE (Rất lớn - Tablet 10\"+)";
                break;
            default:
                sizeCategory = "UNKNOWN (" + screenLayout + ")";
        }

        // Thêm thông tin orientation
        boolean isPortrait = (config.orientation == Configuration.ORIENTATION_PORTRAIT);
        String orientation = isPortrait ? "Portrait (Dọc)" : "Landscape (Ngang)";

        String msg = "Kích thước màn hình: " + sizeCategory + "\nHướng: " + orientation;
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    // Phân loại mật độ pixel (Density)
    public void getScreenDensity(View view) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics); // API 17+ getRealMetrics

        int densityDpi = metrics.densityDpi;
        float density = metrics.density; // Ratio so với mdpi (1.0 = mdpi)

        String densityCategory;
        switch (densityDpi) {
            case DisplayMetrics.DENSITY_LOW:
                densityCategory = "LDPI (120 dpi)";
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                densityCategory = "MDPI (160 dpi) - Baseline";
                break;
            case DisplayMetrics.DENSITY_HIGH:
                densityCategory = "HDPI (240 dpi)";
                break;
            case DisplayMetrics.DENSITY_XHIGH:
                densityCategory = "XHDPI (320 dpi)";
                break;
            case DisplayMetrics.DENSITY_XXHIGH:
                densityCategory = "XXHDPI (480 dpi)";
                break;
            case DisplayMetrics.DENSITY_XXXHIGH:
                densityCategory = "XXXHDPI (640 dpi)";
                break;
            default:
                densityCategory = "CUSTOM (" + densityDpi + " dpi)";
        }

        String msg = String.format("Mật độ pixel: %s\nDensity ratio: %.2f\nWidth: %dpx\nHeight: %dpx",
                densityCategory, density, metrics.widthPixels, metrics.heightPixels);
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}

Bảng phân loại kích thước màn hình (Screen Size Categories):

CategoryKích thước ước lượngVí dụ thiết bịMinimum dp
small< 3.5 inchPhone cũ, Galaxy Pocket426 x 320 dp
normal3.5 - 5 inchPhần lớn phone hiện nay470 x 320 dp
large5 - 7 inchTablet 7", Phablet640 x 480 dp
xlarge> 7 inchTablet 10", Desktop mode960 x 720 dp

Bảng mật độ pixel (Density Buckets):

BucketDPIRatioIcon launcher (px)
ldpi1200.75x36x36
mdpi1601.0x (baseline)48x48
hdpi2401.5x72x72
xhdpi3202.0x96x96
xxhdpi4803.0x144x144
xxxhdpi6404.0x192x192

Bước 4: Manifest

<?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

Chạy app, nhấn 2 nút để xem Screen Size Category và Screen Density của thiết bị.

Cách xác định loại kích thước màn hình Android (small, normal, large, xlarge) bằng code

Ứng dụng thực tế: Alternative Resources

Thay vì check code, hãy dùng resource qualifiers tự động:

  • res/layout/ - default (normal)
  • res/layout-sw600dp/ - màn hình rộng ≥ 600dp (tablet 7")
  • res/layout-sw720dp/ - màn hình rộng ≥ 720dp (tablet 10")
  • res/drawable-hdpi/, drawable-xhdpi/, ... - ảnh theo density
  • res/values-sw600dp/dimens.xml - dimension cho tablet

Kotlin Extension

fun Context.getScreenSizeCategory(): String {
    val config = resources.configuration
    val size = config.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK
    return when (size) {
        Configuration.SCREENLAYOUT_SIZE_SMALL -> "SMALL"
        Configuration.SCREENLAYOUT_SIZE_NORMAL -> "NORMAL"
        Configuration.SCREENLAYOUT_SIZE_LARGE -> "LARGE"
        Configuration.SCREENLAYOUT_SIZE_XLARGE -> "XLARGE"
        else -> "UNKNOWN"
    }
}

fun Context.getDensityCategory(): String {
    val dm = resources.displayMetrics
    return when (dm.densityDpi) {
        DisplayMetrics.DENSITY_LOW -> "LDPI"
        DisplayMetrics.DENSITY_MEDIUM -> "MDPI"
        DisplayMetrics.DENSITY_HIGH -> "HDPI"
        DisplayMetrics.DENSITY_XHIGH -> "XHDPI"
        DisplayMetrics.DENSITY_XXHIGH -> "XXHDPI"
        DisplayMetrics.DENSITY_XXXHIGH -> "XXXHDPI"
        else -> "CUSTOM_${dm.densityDpi}"
    }
}