Ví dụ này minh họa cách hỗ trợ nhiều kích thước màn hình (screen sizes) trên Android bằng cách lấy thông tin kích thước màn hình theo dp.
Bước 1: Tạo dự án mới
Tạo dự án mới trong Android Studio: File → New Project, điền đầy đủ thông tin.
Bước 2: Cấu hình layout (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_screen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="16sp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Bước 3: Code MainActivity (src/MainActivity.java)
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.widget.TextView;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Tính kích thước màn hình theo dp
float dpWidth = (metrics.widthPixels * 160f) / metrics.xdpi;
float dpHeight = (metrics.heightPixels * 160f) / metrics.ydpi;
TextView tvScreen = findViewById(R.id.tv_screen);
tvScreen.setText(String.format("Kích thước màn hình: %d x %d dp", (int)dpWidth, (int)dpHeight));
}
}
Bước 4: Cấu hình Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.app.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 để xem kích thước màn hình hiển thị theo dp. Điều này giúp thiết kế layout responsive cho nhiều kích thước màn hình.