我是靠谱客的博主 温暖雪糕,这篇文章主要介绍Activity添加扩展,现在分享给大家,希望可以做个参考。

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

Activity添加扩展函数

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/** * 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) 复制代码

使用扩展

复制代码
1
2
3
4
5
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingContentView(R.layout.activity_main) } 复制代码

转载于:https://juejin.im/post/5c4fb4f0e51d4535f0191949

最后

以上就是温暖雪糕最近收集整理的关于Activity添加扩展的全部内容,更多相关Activity添加扩展内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部