Activity添加扩展

286 阅读1分钟

Kotlin 同 C# 与 Gosu 类似,能够扩展一个类的新功能而无需继承该类或使用像装饰者这样的任何类型的设计模式。 这通过叫做 扩展 的特殊声明完成。Kotlin 支持 扩展函数 与 扩展属性。

Activity添加扩展函数

/**
 * The `fragment` is added to the container view with id `frameId`. The operation is
 * performed by the `fragmentManager`.
 */
fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int) {
    supportFragmentManager.transact {
        replace(frameId, fragment)
    }
}

/**
 * The `fragment` is added to the container view with tag. The operation is
 * performed by the `fragmentManager`.
 */
fun AppCompatActivity.addFragmentToActivity(fragment: Fragment, tag: String?=null) {
    supportFragmentManager.transact {
        add(fragment, tag)
    }
}

fun AppCompatActivity.addFragmentToActivity(@IdRes containerViewId: Int, fragment: Fragment){
    supportFragmentManager.transact {
        add(containerViewId, fragment)
    }
}

fun AppCompatActivity.setupActionBar(@IdRes toolbarId: Int, action: ActionBar.() -> Unit) {
    setSupportActionBar(findViewById(toolbarId))
    supportActionBar?.run {
        action()
    }
}

fun <T : ViewDataBinding> AppCompatActivity.bindingContentView(@LayoutRes layoutId: Int): T {
    return DataBindingUtil.setContentView(this, layoutId)
}


fun <T : ViewModel> AppCompatActivity.obtainViewModel(viewModelClass: Class<T>) =
        ViewModelProviders.of(this).get(viewModelClass)

使用扩展

  override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindingContentView(R.layout.activity_main)
    }