一、前言
Fragment
传递参数除了使用FragmentFactory
之外,还有一种传统的arguments
的方式。
二、代码演示
1、修改MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
val fragmentFactory = BlankFragmentFactory("====")
supportFragmentManager.fragmentFactory = fragmentFactory
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bundle = Bundle().apply {
putString("key2"," value2")
}
supportFragmentManager.beginTransaction()
.add(R.id.container, BlankFragment::class.java, bundle)
.commit()
}
}
2、修改BlankFragment
class BlankFragment(val content: String) : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val key1 = arguments?.get("key1")
val key2 = arguments?.get("key2")
Log.e("YM","--->接收的key1:$key1")
Log.e("YM","--->接收的key2:$key2")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_blank, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.e("YM","--->获取的内容:$content")
}
}
3、FragmentFactory中使用
其实这种使用方式和FragmentFactory
没有关系,但是为了开拓思路记录一下。另外该方式和动态提交不能同时使用,否则数据会冲掉,这里没有做单独处理。
class BlankFragmentFactory(val content: String): FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String): Fragment {
if (className == BlankFragment::class.java.name) {
return BlankFragment(content).apply {
arguments = arguments?.apply {
putString("key1","value1")
}
}
}
return super.instantiate(classLoader, className)
}
}