中文 | English
AndroidScreenAdapt is a screen adaptation library for modern Android projects (published module :autosize, Maven coordinates io.github.donglua.adapt:autosize), preserving the ByteDance dynamic DisplayMetrics adaptation formula as a modern replacement for the legacy AndroidAutoSize architecture.
The library combines current-Window dynamic DisplayMetrics adaptation with localized Context (fontScale only) and Compose LocalDensity isolation: it provides a clean Kotlin-first API (with full Java interoperability), current-Window bounds resolution, native mode, short-side adaptation for foldables and landscape screens, Android 14+ non-linear font-scaling mitigation, and rotation race-condition guards.
Instead of modifying global Configuration.densityDpi inside attachBaseContext as a blanket replacement for DisplayMetrics, AndroidScreenAdapt avoids three pitfalls:
- Avoids resource qualifier bucket drift caused by integer
densityDpi:DisplayMetrics.densityis a high-precisionFloat, whereasConfiguration.densityDpiis anInt. MutatingdensityDpishifts the resource qualifier buckets resolved by the system (e.g., dropping fromxxhdpitoxhdpior matching the wrongswXXXdplayout). attachBaseContexthas no real Window dimensions yet: An Activity is not attached to a Window atattachBaseContexttime, so real dimensions cannot be obtained under split-screen, freeform windows, or foldable resize events, andattachBaseContextdoes not re-run when window bounds change dynamically.- Avoids
AppCompatActivityand OEM ROM compatibility risks: Overriding the fullConfigurationinattachBaseContextfrequently conflicts withAppCompatDelegateuiMode(dark mode), locale switching, andWebViewresource loading on certain devices.
Accordingly, the library adopts only two safe, localized isolation capabilities while keeping ScreenAdapt as the unified coordinator:
ScreenAdapt.wrapContext/applyOverrideConfigurationlocks onlyfontScale: Uses an empty-deltaConfigurationoverridingfontScalewithout modifyingdensityDpi, preventing Android 14+fontScaleConverternon-linear scaling at the system source.- Localized
LocalDensityoverride for Compose: The core library has zero dependency on Compose runtime and provides a read-onlyScreenAdapt.resolveTargetMetricsAPI so pages can applyCompositionLocalProvider(LocalDensity provides ...)locally.
- Explicit, idempotent initialization: Does not register any
ContentProviderin the mergedAndroidManifest.xml. CallScreenAdapt.initinApplication#onCreateor conditionally by device form factor. - Current Window as the single source of truth: Removes process-wide cached screen dimensions and computes metrics from each target Activity's current Window (
WindowMetricson API 30+,Display#getMetricson older APIs), with automatic fallback to window short side in split-screen/freeform windows. - Foreground-safe
Applicationmetrics sync: SynchronizesApplicationmetrics only during isolated creation or when an Activity is resumed in single-window mode, preventing multi-window or background pages from overwriting each other. Native mode (AdaptDirective.Native/NoAdapt/applyNative) restores only the targetActivityand never writes toApplication(see API Documentation). - Event-driven correction + O(1) fast verification: Corrects drift via lifecycle callbacks, configuration changes, and
OnGlobalLayout, paired with zero-allocationScreenAdapt.ensureApplied(activity)for basegetResources()protection (no background polling threads). - AndroidX Fragment & MIUI support: Supports Fragment-level
AdaptTarget/NoAdaptoverrides and built-in MIUImTmpMetricssynchronization.
dependencies {
implementation("io.github.donglua.adapt:autosize:0.2.0")
}class App : Application() {
override fun onCreate() {
super.onCreate()
ScreenAdapt.init(this) {
designSize(360f, 640f)
excludeFontScale(true)
customFragment(true)
}
}
}open class BaseActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ScreenAdapt.wrapContext(newBase))
}
override fun getResources(): Resources {
ScreenAdapt.ensureApplied(this)
return super.getResources()
}
}If your host app performs pre-adaptation hardware density correction in
attachBaseContext, keep it beforeScreenAdapt.wrapContext.
class ComposePageActivity : ComponentActivity(), NoAdapt {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ScreenAdapt.wrapContext(newBase))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val context = LocalContext.current
val configuration = LocalConfiguration.current
val target = remember(context, configuration) {
ScreenAdapt.resolveTargetMetrics(context, AdaptDirective.Width(360f))
}
val density = target?.let { Density(it.density, it.fontScale) } ?: LocalDensity.current
CompositionLocalProvider(LocalDensity provides density) {
// Composable UI
}
}
}
}The engine computes metrics from the current Window and automatically tracks window changes (fold/unfold, OEM MagicWindow/letterboxing, split-screen resizing, orientation changes), while tier thresholds or native fallbacks for large/unusual screens should be defined in strategy to match your product design. ScreenAdapt.getWindowInfo(activity), ScreenAdapt.getNativeDensity(activity), and activity.resources.configuration are refreshed before strategy runs and can be read safely inside it:
ScreenAdapt.init(this) {
designSize(375f, 667f)
excludeFontScale(true)
strategy { _, activity ->
val info = ScreenAdapt.getWindowInfo(activity) ?: return@strategy null
val w = info.widthPx
val h = info.heightPx
if (w <= 0 || h <= 0) return@strategy null
val shortPx = minOf(w, h)
val longPx = maxOf(w, h)
val realShort = minOf(info.realWidthPx, info.realHeightPx)
val realLong = maxOf(info.realWidthPx, info.realHeightPx)
val ratio = w.toFloat() / h.toFloat()
// Detect split-screen, freeform, and OEM MagicWindow/letterboxed windows
// (where activity.isInMultiWindowMode may still report false).
val isSubWindow = info.inMultiWindow ||
(realShort > 0 && shortPx < realShort * 0.85f) ||
(realLong > 0 && longPx < realLong * 0.85f)
val swDp = activity.resources.configuration.smallestScreenWidthDp
val nativeDensity = ScreenAdapt.getNativeDensity(activity)
val isTabletDevice = swDp >= 600 && (realLong.toFloat() / realShort.coerceAtLeast(1)) > 1.2f
when {
// 1. Near-square unfolded foldable (e.g., Mate X5/X6 inner display)
!isSubWindow && w > 1500 && ratio in 0.85f..1.15f ->
AdaptDirective.Width(750f)
// 2. Fullscreen tablets / tri-foldables (excluding constrained MagicWindow/freeform sub-windows):
// scale to 750dp or return AdaptDirective.Native for responsive layouts.
!isSubWindow && (
(isTabletDevice && shortPx >= 1500) ||
(shortPx >= 1500 && nativeDensity in 0.1f..2.5f) ||
shortPx >= 2000
) -> AdaptDirective.ShortSide(750f, useRealDisplay = false)
// 3. High-PPI wide-foldable inner display (e.g., 7-8" wide foldables): 600dp short side
// to avoid sudden font shrinkage from falling into the tablet 750dp bucket.
!isSubWindow && shortPx >= 1500 ->
AdaptDirective.ShortSide(600f, useRealDisplay = false)
// 4. MagicWindow and split/freeform sub-windows: scale strictly by 375dp window short side
// without applying short-screen protection.
isSubWindow ->
AdaptDirective.ShortSide(375f, useRealDisplay = false)
// 5. Fullscreen phones (portrait/landscape) and short/square cover screens:
// 375dp base with short-screen protection relaxing short side up to 420dp.
else -> {
val effectiveShortDp = ((shortPx.toFloat() / longPx.toFloat()) * 667f)
.coerceIn(375f, 420f)
AdaptDirective.ShortSide(effectiveShortDp, useRealDisplay = true)
}
}
}
}Notes:
- Thresholds above (
375f / 420f / 600f / 750f,667f,1500px,2.5f) are reference examples—adjust them to match your design specs. If tablets (including MagicWindow) should use native responsive layouts, returnAdaptDirective.Nativefor tablets or skip callingScreenAdapt.init(...)inApplication#onCreate(ScreenMetricsremains safe to call).- Short-screen protection is intended only for fullscreen short/square displays, not
isSubWindow; otherwise a shorter freeform or split-screen window will widen the effective design size and shrinkdensityeven when window width has not narrowed.- Always return
AdaptDirective.Native(neverAdaptDirective.Skip) to opt out of scaling:Skipleaves the previousDisplayMetricsuntouched, so rotating without Activity recreation (for instance, entering a centered MagicWindow on a tablet) would retain the portrait density and clip the UI.- To handle fold/unfold, MagicWindow transitions, or rotation without recreating the
Activity, declareandroid:configChanges="orientation|screenSize|smallestScreenSize|screenLayout"inAndroidManifest.xml; the engine will automatically recalculate density on configuration and layout changes.
See API Documentation for full signatures, configuration options, directives, and ScreenMetrics utilities.
:autosize: Published AAR module containing the pure-JVM calculation packagecn.jingzhuan.adapt.autosize.core(zeroandroid.*/androidx.*dependencies) and runtime enginecn.jingzhuan.adapt.autosize.engine.:consumer-test: Kotlin DSL and Java Builder consumer compilation and contract tests.:sample: Sample app covering Fragment switching,ShortSide+AdaptEventListener,NoAdapt,wrapContext, ComposeLocalDensity, and R8 minification checks.
# Run unit tests, contract tests, core isolation, API baseline, AAR checks, and R8 sample build
./gradlew check
# Run instrumentation tests on a connected device/emulator (including R8 minified release test)
./gradlew :autosize:connectedDebugAndroidTest :sample:connectedDebugAndroidTest
./gradlew :sample:connectedReleaseAndroidTest -PminifiedTest=trueLicensed under the Apache-2.0 License (see LICENSE). See NOTICE for acknowledgments to JessYan/AndroidAutoSize (portions of the original design ideas and scaling formulas are derived from its Apache-2.0 implementation).