Skip to content

Instantly share code, notes, and snippets.

@Yazon2006
Created January 31, 2018 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yazon2006/1cbc864d162588d3a577f5043b390a46 to your computer and use it in GitHub Desktop.
Save Yazon2006/1cbc864d162588d3a577f5043b390a46 to your computer and use it in GitHub Desktop.
FragmentContainer that allow to use fitsSystemWindow in fragments that added using fragment transaction
package com.imslp.app.presentation.base
import android.content.Context
import android.graphics.Rect
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
/**
* A FrameLayout subclass that dispatches WindowInsets to its children instead of adjusting its padding.
* Useful for Fragment containers.
*
* See details at https://medium.com/google-developers/why-would-i-want-to-fitssystemwindows-4e26d9ce1eec
* and https://stackoverflow.com/questions/31190612/fitssystemwindows-effect-gone-for-fragments-added-via-fragmenttransaction/34345286
*/
class FragmentContainer @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) {
private var windowInsets = Rect()
override fun fitSystemWindows(insets: Rect): Boolean {
windowInsets.set(insets)
super.fitSystemWindows(insets)
return false
}
override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) {
super.addView(child, index, params)
super.fitSystemWindows(windowInsets)
}
public override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val savedState = SavedState(superState)
savedState.stateToSave = this.windowInsets
return savedState
}
public override fun onRestoreInstanceState(state: Parcelable) {
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
this.windowInsets = state.stateToSave
super.fitSystemWindows(windowInsets)
}
internal class SavedState : View.BaseSavedState {
var stateToSave: Rect = Rect()
constructor(superState: Parcelable) : super(superState)
private constructor(parcel: Parcel) : super(parcel) {
this.stateToSave = parcel.readParcelable(Rect::class.java.classLoader)
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeParcelable(this.stateToSave, Parcelable.PARCELABLE_WRITE_RETURN_VALUE)
}
companion object CREATOR : Parcelable.Creator<SavedState> {
override fun createFromParcel(parcel: Parcel): SavedState {
return SavedState(parcel)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment