diff --git a/app/src/main/java/com/ray650128/floatingwindow/DensityExtension.kt b/app/src/main/java/com/ray650128/floatingwindow/DensityExtension.kt new file mode 100644 index 0000000..6fdc956 --- /dev/null +++ b/app/src/main/java/com/ray650128/floatingwindow/DensityExtension.kt @@ -0,0 +1,9 @@ +package com.ray650128.floatingwindow + +import android.content.res.Resources + +val Int.dp: Int + get() = (this * Resources.getSystem().displayMetrics.density).toInt() + +val Int.px: Int + get() = (this / Resources.getSystem().displayMetrics.density).toInt() \ No newline at end of file diff --git a/app/src/main/java/com/ray650128/floatingwindow/utils/DensityUtil.kt b/app/src/main/java/com/ray650128/floatingwindow/utils/DensityUtil.kt new file mode 100644 index 0000000..70a7117 --- /dev/null +++ b/app/src/main/java/com/ray650128/floatingwindow/utils/DensityUtil.kt @@ -0,0 +1,77 @@ +package com.ray650128.floatingwindow.utils + +import android.content.Context +import android.os.Build +import android.util.DisplayMetrics +import android.view.WindowManager +import com.ray650128.floatingwindow.MyApp + + +/** + * 畫面尺寸相關工具類別。 + */ +object DensityUtil { + + /** + * 取得螢幕寬度 + * @return 螢幕寬度(px) + */ + fun getScreenWidth(): Int { + val windowManager = MyApp.appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager + + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val windowMetrics = windowManager.currentWindowMetrics + windowMetrics.bounds.width() + } else { + val metric = DisplayMetrics() + windowManager.defaultDisplay.getMetrics(metric) + metric.widthPixels + } + } + + /** + * 取得螢幕高度 + * @return 螢幕高度(px) + */ + fun getScreenHeight(): Int { + val windowManager = MyApp.appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager + + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val windowMetrics = windowManager.currentWindowMetrics + windowMetrics.bounds.height() + } else { + val metric = DisplayMetrics() + windowManager.defaultDisplay.getMetrics(metric) + metric.heightPixels + } + } + + /** + * 取得狀態列高度 + * @return 狀態列高度(px) + */ + fun getStatusBarHeight(): Int { + var result = 0 + val resourceId: Int = MyApp.appContext.resources.getIdentifier( + "status_bar_height", + "dimen", + "android" + ) + if (resourceId > 0) { + result = MyApp.appContext.resources.getDimensionPixelSize(resourceId) + } + return result + } + + /** + * 取得導航列高度 + * @return 導航列高度(px) + */ + fun getNavigationBarHeight(): Int { + val resources = MyApp.appContext.resources + val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android") + return if (resourceId > 0) { + resources.getDimensionPixelSize(resourceId) + } else 0 + } +} \ No newline at end of file