本文介绍了Kotlin-创建片段newInstance模式的惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android上创建Fragment的最佳实践是使用静态工厂方法,并通过setArguments()Bundle中传递参数.

The best practice on Android for creating a Fragment is to use a static factory method and pass arguments in a Bundle via setArguments().

在Java中,此操作类似于:

In Java, this is done something like:

public class MyFragment extends Fragment {
    static MyFragment newInstance(int foo) {
        Bundle args = new Bundle();
        args.putInt("foo", foo);
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }
}

在科特林,这可以转换为:

In Kotlin this converts to:

class MyFragment : Fragment() {
    companion object {
       fun newInstance(foo: Int): MyFragment {
            val args = Bundle()
            args.putInt("foo", foo)
            val fragment = MyFragment()
            fragment.arguments = args
            return fragment
        }
    }
}

使用Java支持互操作是有意义的,因此仍可以通过MyFragment.newInstance(...)调用它,但是如果我们不必担心Java互操作,那么在Kotlin中还有一种更惯用的方法吗?

This makes sense to support interop with Java so it can still be called via MyFragment.newInstance(...), but is there a more idiomatic way to do this in Kotlin if we don't need to worry about Java interop?

推荐答案

我喜欢这样:

companion object {
    private const val MY_BOOLEAN = "my_boolean"
    private const val MY_INT = "my_int"

    fun newInstance(aBoolean: Boolean, anInt: Int) = MyFragment().apply {
        arguments = Bundle(2).apply {
            putBoolean(MY_BOOLEAN, aBoolean)
            putInt(MY_INT, anInt)
        }
    }
}

使用KotlinX扩展,您也可以这样做

with KotlinX extensions, you can also do this

companion object {
    private const val MY_BOOLEAN = "my_boolean"
    private const val MY_INT = "my_int"

    fun newInstance(aBoolean: Boolean, anInt: Int) = MyFragment().apply {
        arguments = bundleOf(
            MY_BOOLEAN to aBoolean,
            MY_INT to anInt)
    }
}

这篇关于Kotlin-创建片段newInstance模式的惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:29