Android 干货 --- 丢掉你老旧的参数传递方式,投入 Bracer 的怀抱吧。
//oh shit, wtf!! 写错了 key 的名字,导致一直获取不到值 val valueA = intent.getStringExtra("key_l")
}}再或者,这样?
//Oh my god! 每个 Fragment 都要这么写一遍吗?class FragmentA : Fragment() {var a: String = ""var b: String = ""
companion object {fun newFragment(a: String, b: String): FragmentA {val fragmentA = FragmentA()val bundle = Bundle()bundle.putString("key_a", a)bundle.putString("key_b", b)fragmentA.arguments = bundlereturn fragmentA}}
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)arguments?.let {a = it.getString("key_a") ?: ""b = it.getString("key_b") ?: ""}}}只是想简单传个参数,写这么多代码真的好累!
没事,现在有了 Bracer,分分钟减轻你的工作量!
来看看新世纪如何正确传递参数!
在 Fragment 中获取参数:
class MutableParamsFragment : Fragment() {//基本类型 var intParams by mutableParams<Int>()var booleanParams by mutableParams<Boolean>()var stringParams by mutableParams<String>()
//自定义类型 var customParams by mutableParams<CustomParams1>()
//listvar intListParams by mutableParams<ArrayList<Int>>()var stringListParams by mutableParams<ArrayList<String>>()
//arrayvar intArrayParams by mutableParams<IntArray>()var arrayCustomParams by mutablePa
rams<Array<CustomParams1>>()
//其他任意类型//...
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
//直接使用,不需要再手动从 Arguments 中读取了 println(intParams)println(booleanParams)println(stringParams)println(customParams)println(intListParams)println(stringListParams)println(intArrayParams)
}}如你所见,从 Fragment 里获取参数就是这么简单,并且非常安全!!
并且支持几乎所有的类型!
你不会再遇到空指针 null,所有的参数都会有默认值;不会遇到 key 写错的情况,所有的参数默认都以自身的名字作为 key.
等同于:val byteParams = arguments.getByte("byteParams", 0)var stringParams = arguments.getString("stringParams") ?: ""
接下来我们来见识一下如何传递参数:
val fragment = MutableParamsFragment().apply {intParams = 1 //赋值即可 booleanParams = truestringParams = "123"
customParams = CustomParams1()intListParams = arrayListOf(1,2,3)
intArrayParams = IntArray(2) { it }}
//show this Fragmentval beginTransaction = supportFragmentManager.beginTransaction()beginTransaction.add(R.id.frameLayout, fragment, "")beginTransaction.commit()
Amazing!! 是的就是这么神奇,传递参数就是这么简单!
Double Kill 接下来看一下 Activity 的情况吧
class MutableParamsActivity : AppCompatActivity() {//基本类型 var intParams by mutableParams<Int>()var booleanParams by mutableParams<Boolean>()var stringParams by mutableParams<String>()
//自定义类型 var customParams by mutableParams<CustomParams1>()
//listvar intListParams by mutableParams<ArrayList<Int>>()var stringListParams by mutableParams<ArrayList<String>>()
//arrayvar intArrayParams by mutableParams<IntArray>()var arrayCustomParams by mutableParams<Array<CustomParams1>>()
评论