Get the size of my homescreen widget

前端 未结 6 2090
没有蜡笔的小新
没有蜡笔的小新 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 15:59

    Get cols/rows count (Kotlin):

    val options = appWidgetManager.getAppWidgetOptions(appWidgetId)
    val minHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
    val maxHeight = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
    
    val oneCellHeight = ViewExtensions.convertDpToPx(40f * 1, context).toInt() - (30 * 1)
    val twoCellHeight = ViewExtensions.convertDpToPx(40f * 2, context).toInt() - (30 * 2)
    val threeCellHeight = ViewExtensions.convertDpToPx(40f * 3, context).toInt() - (30 * 3)
    val fourCellHeight = ViewExtensions.convertDpToPx(40f * 4, context).toInt() - (30 * 4)
    
    when {
        oneCellHeight in (minHeight..maxHeight) -> {
            // 1 cell
        }
        twoCellHeight in (minHeight..maxHeight) -> {
            // 2 cells
        }
        threeCellHeight in (minHeight..maxHeight) -> {
            // 3 cells
        }
        fourCellHeight in (minHeight..maxHeight) -> {
            // 4 cells
        }
        else -> {
            // More
        }
    }
    
    class ViewExtensions {
        companion object {
            fun convertDpToPx(sp: Float, context: Context): Float {
                return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sp, context.resources.displayMetrics)
            }
        }
    }
    

    Based on, that 1 cell = 40dp

    https://developer.android.com/guide/practices/ui_guidelines/widget_design.html#anatomy_determining_size

提交回复
热议问题