简体   繁体   English

将可空值从 Activity 传递到 Fragment

[英]Passing Nullable Values from Activity to Fragment

When passing Strings from an activity to a fragment usingStrings从活动传递到片段时使用

Bundle args = new Bundle();
args.putString(key, value);
fragment.setArguments(args);

I can also pass potential null and receive it in the fragment with我还可以传递潜在的null并在片段中接收它

String string = getArguments().getString(key);

I'd also like to pass nullable Float s and Integer s but the corresponding putInt() and putFloat() methods don't allow passing null .我倒是也想通过为空的Float S和Integer秒,但相应的putInt()putFloat()方法不允许传球null I am now passing additional flags as arguments that indicate whether a value is set or not but that seems rather clumsy in comparison.我现在正在传递额外的标志作为参数,指示是否设置了一个值,但相比之下,这似乎相当笨拙。 Is there a better way to pass potential null values (preferably available in API level 14 and later)?有没有更好的方法来传递潜在的空值(最好在 API 级别 14 及更高版本中可用)?

I prefer to skip putting something in case of null into bundle. 我更喜欢跳过将为null情况放入捆绑包中的操作。
In fragment just check Bundle.containsKey(String key) , if doesn't means null . 在片段中,只需检查Bundle.containsKey(String key) ,如果不意味着null

This is the Kotlin version of @Eugene Krivenjas textual solution - just in case someone prefers copy/pasting to thinking ;)这是@Eugene Krivenjas 文本解决方案的 Kotlin 版本 - 以防万一有人更喜欢复制/粘贴而不是思考;)

private fun Bundle.putLongOrSkip(key: String?, value: Long?) =
    apply { value?.let { putLong(key, value) } }

private fun Bundle.getLongOrNull(key: String?) = 
    if (containsKey(key)) getLong(key) else null

Ofc this is possible for floats and ints , too. Ofc 这对于floatsints也是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM