Вы можете сохранить предыдущую яркость в переменной в пределах Fragment
.Когда Fragment
удаляется, он будет вызывать onDestroy()
, что является хорошим временем для сброса яркости.
И в качестве примечания, когда вы пишете в Kotlin, попробуйте воздержаться отиспользуя !!
.Вы должны обращаться со случаем изящно, если он нулевой.С ?.let
вы можете записать его, поэтому он будет изменять яркость только в том случае, если Activity
не равно нулю (it
- это Activity
в данном случае).
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()
}
}