- 打印Log
Log.d(TAG , "print i = $i , j = $j , len = ${str.length} ")
- 设置 listeners
myButton.setOnClickListener { navigateToDetail() }
- for 语句中的范围
在Java 中 :
在Kotlin 中 :for (int i = 1; i <= 10 ; i++) { } for (int i = 1; i < 10 ; i++) { } for (int i = 10; i >= 0 ; i--) { } for (int i = 1; i <= 10 ; i+=2) { } for (int i = 10; i >= 0 ; i-=2) { } for (String item : collection) { } for (Map.Entry<String, String> entry: map.entrySet()) { }
for (i in 1..10) { } for (i in 1 until 10) { } for (i in 10 downTo 0) { } for (i in 1..10 step 2) { } for (i in 10 downTo 1 step 2) { } for (item in collection) { } for ((key, value) in map) { }
- 参数个数不定的函数
在Java 中我们可以定义参数个数不固定的函数 :
而在Kotlin中我们要用 vararg 关键字 , 使用上是一样的 :void doSomething(int... numbers) { }
fun doSomething(vararg numbers: Int) { }
- Handler、Thread可以写得更简洁
view.postDelayed({ doWhatever() }, 200) Thread().run { // Running in a thread }
- 省去一些不必要的代码
一般在java中我们经常要判断一个类对象是否为空,而在kotlin 中,对象一般是非空的,除非你定义时加了?号,这样在代码中就不必要经常加空判断了。
而kotlin对空的判断也很简洁 :val str : String = null //报错 val str : String? = null //正常
val nullStr : String? = null val size : Int = nullStr?.length ?: 0 // 如果nullStr为空就返回0
- 解析布局
我们以前用java在inflate一个布局时,一般是这样写的 :
在Kotlin中,我们可以定义扩展函数 :LayoutInflater.from(parent.getContext()).inflate(R.id.my_layout, parent, false);
这样在代码中我们就可以这样使用它 :fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) }
parent.inflate(R.layout.my_layout) parent.inflate(R.layout.my_layout, true)
- ImageView 加载网络图片
我们仍然为ImageView 定义一个扩展函数,使用你的加载图片的库,比如Picasso:
这样在代码中我们就可以这样使用它 :fun ImageView.loadUrl(url: String) { Picasso.with(context).load(url).into(this) }
imageView.loadUrl("http://..../")
- 处理Options Menu
在Java时,在处理多个选择时我们一般用 switch,而在Kotlin中,我们可以用when 语句 :
其中consume 函数是一个 inline 函数 :override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> consume { navigateToSettings() } R.id.nav_camera -> drawer.consume { navigateToCamera() } R.id.nav_gallery -> drawer.consume { loadGallery() } R.id.nav_slideshow -> drawer.consume { loadSlideshow() } else -> super.onOptionsItemSelected(item) }
inline fun consume(f: () -> Unit): Boolean { f() return true }
- 初始化控件
在Java时,我们一般要在setContentView之后再调用findViewByID初始化控件,而在Kotlin中可以用lazy懒加载 :override val textView by lazy { findViewById(R.id.sample_text) as TextView } override val dataBase by lazy { DataBase(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail) textView.setText(R.string.text) dataBase.loadWhatever() }
- 处理集合类
Kotlin中的集合类提供了很多处理函数,方便我们调用,比如 filter、sort、map.return parsedContacts.filter { it.name != null && it.image != null } .sortedBy { it.name } .map { Contact(it.id, it.name!!, it.image!!) ] }
- 定义 数据类
一般在Java定义数据类时,getters, setters, toString(), equals() ... 都需要我们自己编写,在Kotlin就不用这么麻烦了。data class Person(val name: String, val surname: String, val age: Int)
- 定义常量
object DefaultValues { val FILES_TO_DOWNLOAD = 100 } class DefaultValues private constructor() { companion object { val FILES_TO_DOWNLOAD = 100 } } // 只能在 top level const val DEFAULT_FILES_TO_DOWNLOAD = 100
- 定义单例
class Singleton private constructor() { private object Holder { val INSTANCE = Singleton() } companion object { val instance: Singleton by lazy { Holder.INSTANCE } } }
Android 使用 Kotlin 的一些技巧
原文链接:
www.jianshu.com