Kotlin从入门到放弃Kotlin官方文档Kotlin

Android 使用Kotlin的一些技巧

2017-06-18  本文已影响452人  兰兰笑笑生
Log.d(TAG , "print i = $i , j = $j , len = ${str.length} ")
myButton.setOnClickListener { navigateToDetail() }
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()) { }

在Kotlin 中 :

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) { }
void doSomething(int... numbers) { }

而在Kotlin中我们要用 vararg 关键字 , 使用上是一样的 :

fun doSomething(vararg numbers: Int) { }
view.postDelayed({ doWhatever() }, 200)
Thread().run { 
    // Running in a thread    
}
val str : String = null   //报错
val str : String? = null  //正常

而kotlin对空的判断也很简洁 :

val nullStr : String? = null
val size : Int = nullStr?.length ?: 0  // 如果nullStr为空就返回0
LayoutInflater.from(parent.getContext()).inflate(R.id.my_layout, parent, false);

在Kotlin中,我们可以定义扩展函数 :

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)
fun ImageView.loadUrl(url: String) {
    Picasso.with(context).load(url).into(this)
}

这样在代码中我们就可以这样使用它 :

imageView.loadUrl("http://..../")
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)
}

其中consume 函数是一个 inline 函数 :

inline fun consume(f: () -> Unit): Boolean {
    f()
    return true
}
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()
}
return parsedContacts.filter { it.name != null && it.image != null }
        .sortedBy { it.name }
        .map { Contact(it.id, it.name!!, it.image!!) ]
}
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
       }
  }
}

参考

Kotlin awesome tricks for Android
kotlin vs java

上一篇 下一篇

猜你喜欢

热点阅读