Get the size of my homescreen widget

前端 未结 6 2028
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 15:46

I just want to know how big my current widget is. I found tons of questions to set the minimum size, but I don\'t want to set it. Instead I want to show that informations which

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 16:05

    Here is class helper to get widget size in pixels

    Note that you should use Application context, otherwise orientation will be incorrect on widget rotation

    class WidgetSizeProvider(
        private val context: Context // Do not pass Application context
    ) {
    
        private val appWidgetManager = AppWidgetManager.getInstance(context)
    
        fun getWidgetsSize(widgetId: Int): Pair {
            val isPortrait = context.resources.configuration.orientation == ORIENTATION_PORTRAIT
            val width = getWidgetWidth(isPortrait, widgetId)
            val height = getWidgetHeight(isPortrait, widgetId)
            val widthInPx = context.dip(width)
            val heightInPx = context.dip(height)
            return widthInPx to heightInPx
        }
    
        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)
    
        private fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()
    
    }
    

提交回复
热议问题