Skip to content

Instantly share code, notes, and snippets.

@eliasto
Created September 16, 2024 09:12
Show Gist options
  • Select an option

  • Save eliasto/29fd05da6c147cc58382e7283bf77d47 to your computer and use it in GitHub Desktop.

Select an option

Save eliasto/29fd05da6c147cc58382e7283bf77d47 to your computer and use it in GitHub Desktop.
WidgetSizeProvider.kt
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.res.Configuration
class WidgetSizeProvider(
private val context: Context
) {
private val appWidgetManager = AppWidgetManager.getInstance(context)
fun getWidgetsSize(widgetId: Int): Pair<Int, Int> {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val width = getWidgetWidth(isPortrait, widgetId)
val height = getWidgetHeight(isPortrait, widgetId)
return width to height
}
fun getWidgetSizeInCells(widgetId: Int): CellWidth {
val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val width = getWidgetWidth(isPortrait, widgetId)
val height = getWidgetHeight(isPortrait, widgetId)
return CellWidth((width + 30) / 70, (height + 30) / 70)
}
private fun getWidgetWidth(isPortrait: Boolean, widgetId: Int): Int = if (isPortrait) {
getWidgetSizeInDp(widgetId, AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
} else {
getWidgetSizeInDp(widgetId, AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
}
private fun getWidgetHeight(isPortrait: Boolean, widgetId: Int): Int = if (isPortrait) {
getWidgetSizeInDp(widgetId, AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
} else {
getWidgetSizeInDp(widgetId, AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
}
private fun getWidgetSizeInDp(widgetId: Int, key: String): Int = appWidgetManager.getAppWidgetOptions(widgetId).getInt(key, 0)
fun getFontScale(): Float = context.resources.configuration.fontScale
}
class CellWidth(val width: Int, val height: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment