通过代码将布局横向显示,达到横屏效果

71 阅读1分钟

要实现这个功能不难,原理就是将需要横屏的View的宽(w)高(y)互换,然后将View移到中心位置,以这个中心位置rotate 90度即可

import android.view.View
import kotlin.math.abs

/**
 * 通过代码将布局横向显示,达到横屏效果
 */
object ViewLandscapeUtil {
    /**
     * 通过代码将布局横向显示,达到横屏效果
     *
     * @param target 要横向显示的View,其父View建议是FrameLayout,否则可能达不到预期效果
     */
    fun landscape(target: View) {
        target.post {
            val width: Int = target.height
            val height: Int = target.width
            target.apply {
                //移动到中心位置
                val translation = abs(width - height) / 2f
                translationX = -translation
                translationY = translation
                //宽高互换
                setLayoutParams(target.layoutParams.also {
                    it.height = height
                    it.width = width
                })
                //旋转90度
                rotation = 90f
            }
        }
    }
}