Snippets

Oleg Chulakov Studio Когда размер имеет значение

Created by Владимир Самсонов last modified
class DisplaySizeGetter {

    companion object {
         fun getSize(display: Display): Point? {
            return SdkType.getInstance(Build.VERSION.SDK_INT).getSize(display)
        }
    }

    enum class SdkType(var sdk: Int) {
        JELLY_BEAN(17) {
            override fun getSize(display: Display): Point? {
                var metrics = DisplayMetrics()
                display.getRealMetrics(metrics)
                return Point(
                    metrics.widthPixels,
                    metrics.heightPixels
                )
            }
        },
        ICE_CREAM_SANDWITCH(14) {
            override fun getSize(display: Display): Point? {
                var outPoint = Point()
                var mGetRawH: Method? = null
                try {
                    mGetRawH = Display::class.java.getMethod("getRawHeight");
                    var mGetRawW = Display::class.java.getMethod("getRawWidth");
                    outPoint.x = mGetRawW.invoke(display) as Int
                    outPoint.y = mGetRawH.invoke(display) as Int
                    return outPoint
                } catch (e: Throwable) {
                    return null
                }
            }
        },
        HONEW_COMB(13) {
            override fun getSize(display: Display): Point? {
                var outPoint = Point()
                display.getSize(outPoint)
                return outPoint
            }
        },
        OLD_SDK(12) {
            override fun getSize(display: Display): Point? {
                return Point(display.getWidth(), display.getHeight())
            }
        };

        companion object {
            fun getInstance(sdk: Int): SdkType {
                for (version in arrayOf(JELLY_BEAN, ICE_CREAM_SANDWITCH, HONEW_COMB, OLD_SDK)) {
                    if (sdk >= version.sdk) return version
                }
                return OLD_SDK
            }
        }

        abstract fun getSize(display: Display): Point?
    }
}

Comments (0)