Skip to content

Instantly share code, notes, and snippets.

View cribetti's full-sized avatar

chris ribetti cribetti

View GitHub Profile
class MyFragment : Fragment() {
private lateinit var arg: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.getString(ARG) ?: ""
}
companion object {
fun newInstance(arg: String) =
MyFragment().apply {
arguments = Bundle().apply {
@NonNull
public static Fragment instantiate(@NonNull Context context, @NonNull String fname, @Nullable Bundle args) {
try {
...
Fragment f = clazz.getConstructor().newInstance();
if (args != null) {
args.setClassLoader(...);
f.setArguments(args);
}
return f;
class MyActivity() : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
val fragment = MyFragment.newInstance("my argument")
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_layout, fragment)
.commitNow()
...
class MyActivity() : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
supportFragmentManager.fragmentFactory = FragmentFactoryImpl()
super.onCreate(savedInstanceState)
...
val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, MyFragment::class.java.name)
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_layout, fragment)
.commitNow()
...
@NonNull
public Fragment instantiate(@NonNull ClassLoader classLoader, @NonNull String className) {
try {
...
return cls.getConstructor().newInstance();
} catch (java.lang.InstantiationException e) {
...
class FragmentFactoryImpl: FragmentFactory() {
val arg = "my argument"
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
return when (className) {
MyFragment::class.java.name -> MyFragment(arg)
else -> super.instantiate(classLoader, className)
}
}
}
class FragmentFactoryImpl(private val arg: String): FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
return when (className) {
MyFragment::class.java.name -> MyFragment(arg)
MyFragment2::class.java.name -> {
MyFragment2().apply {
arguments = Bundle().apply {
putString("key", arg)
}
}
@Deprecated
@NonNull
public static Fragment instantiate(@NonNull Context context, @NonNull String fname, @Nullable Bundle args) {