Last active
January 16, 2020 13:11
-
-
Save osipxd/dd97b1d7e06d99a4f9894469e1fa0d60 to your computer and use it in GitHub Desktop.
Activity wrapper for any fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
android:id="@+id/main_container" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.content.Context | |
import android.content.Intent | |
import android.os.Bundle | |
import androidx.fragment.app.Fragment | |
import com.example.R | |
import com.example.BaseActivity | |
class FragmentContainerActivity : BaseActivity() { | |
companion object { | |
inline fun fromFactory( | |
context: Context, | |
crossinline createFragment: () -> Fragment | |
): Intent { | |
return Intent(context, FragmentContainerActivity::class.java).apply { | |
putFragmentFactory(createFragment) | |
} | |
} | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_fragment_container) | |
if (savedInstanceState == null) { | |
val fragmentFactory = intent.getFragmentFactory() | |
this.changeFragment(fragmentFactory.createFragment()) | |
.commit() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.content.Context | |
import android.content.Intent | |
import androidx.annotation.StringRes | |
import androidx.fragment.app.Fragment | |
import java.io.Serializable | |
const val FRAGMENT_FACTORY = "fragment_factory" | |
interface FragmentFactory : Serializable { | |
fun createFragment(): Fragment | |
} | |
inline fun Intent.putFragmentFactory(crossinline createFragment: () -> Fragment) { | |
val factory = object : FragmentFactory { | |
override fun createFragment(): Fragment = createFragment() | |
} | |
putExtra(FRAGMENT_FACTORY, factory) | |
} | |
fun Intent.getFragmentFactory(): FragmentFactory { | |
return getSerializableExtra(FRAGMENT_FACTORY) as FragmentFactory | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment