Migrate Activity from Java to Kotlin

因为大部分逻辑都在Fragment和ViewModel里,Activity更像一个壳子,代码非常少,所以转成Kotlin就很简单了。

Because almost all the logic are handled in the Fragments & ViewModels, that means Activity is more like a shell just to host the Fragments, so it's quite easy to convert from Java to Kotlin.

public abstract class BaseSingleFragmentActivity extends DaggerAppCompatActivity {

    protected abstract Fragment createFragment();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_fragment_activity);

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);

        if (fragment == null) {
            fragment = createFragment();
            fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
        }
    }
 }

vs

abstract class BaseSingleFragmentActivity : DaggerAppCompatActivity() {

    protected abstract fun createFragment(): Fragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.single_fragment_activity)

        val fm = supportFragmentManager
        var fragment: Fragment? = fm.findFragmentById(R.id.fragmentContainer)

        if (fragment == null) {
            fragment = createFragment()
            fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit()
        }
    }
}

需要注意的一点 val fm = supportFragmentManager 实际调用的仍然是 getSupportFragmentManager()