【问题标题】:Change screen brightness in fragment更改片段中的屏幕亮度
【发布时间】:2018-12-19 05:40:22
【问题描述】:

当我打开一些放置在我的活动中的片段时,我想更改屏幕的亮度,因此我在 onActivityCreated 中放置了此代码(我也尝试将其放置在 onResume 中)。但是当用户关闭此片段时,我想将屏幕恢复到以前的亮度。但目前亮度适用于所有活动。如何仅对片段应用脆性?或者记录亮度结果并在片段关闭时重新运行?

class BrightnessFragment : Fragment(), Injectable {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        appCompatActivity = activity as AppCompatActivity

        val lp = activity!!.window.attributes
        lp.screenBrightness = 1F
        activity!!.window.attributes = lp
    }

    override fun onResume() {
        super.onResume()
    }
}

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    您可以将以前的亮度存储在Fragment 内的变量中。当Fragment被移除时,它会调用onDestroy(),这是重置亮度的好时机。

    附带说明,当您使用 Kotlin 编写代码时,请尽量避免使用 !!。如果它为空,你应该优雅地处理这个案例。使用?.let,您可以编写它,这样它只会在Activity 不为空时改变亮度(在这种情况下itActivity)。

    class BrightnessFragment : Fragment(), Injectable {
    
        companion object {
            // Using a constant to make the code cleaner.
            private const val MAX_BRIGHTNESS = 1F
        }
    
        // Our stored previous brightness.
        private var previousBrightness = MAX_BRIGHTNESS
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            return inflater.inflate(R.layout.fragment, container, false)
        }
    
        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
    
            (activity as? AppCompatActivity)?.let {
                val attributes = it.window.attributes
    
                // Store the previous brightness
                previousBrightness = attributes.screenBrightness
    
                // Set the brightness to MAX_BRIGHTNESS.
                attributes.screenBrightness = MAX_BRIGHTNESS
                it.window.attributes = attributes
            }
        }
    
        override fun onDestroy() {
            (activity as? AppCompatActivity)?.let {
                val attributes = it.window.attributes
    
                // Set the brightness to previousBrightness.
                attributes.screenBrightness = previousBrightness
                it.window.attributes = attributes
            }
            // Don't forget to called super.onDestroy()
            super.onDestroy()
        }
    }
    

    【讨论】:

    • 感谢您!注意
    • 感谢您的回答!顺便说一句,为什么你必须使用(activity as? AppCompatActivity)?.let 而不是简单地使用activity?.let
    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多