更改片段中的屏幕亮度

时间:2018-12-18 20:45:04

标签: android android-fragments

当我打开放置在活动中的某些片段时,我想更改屏幕的亮度,因此我在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()
    }
}

1 个答案:

答案 0 :(得分: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()
    }
}