Anko是一個(gè)方便你用Kotlin時(shí)簡(jiǎn)化Android開發(fā)的一個(gè)庫(kù),分為4個(gè)部分:
- Commons
- Layouts
- SQLite
- Coroutines
今天就來了解下第一個(gè)常規(guī)部分的,首先在項(xiàng)目中添加必要的依賴
compile "org.jetbrains.anko:anko:$anko_version"
或者你可以針對(duì)第一個(gè)添加單獨(dú)的依賴
compile "org.jetbrains.anko:anko-commons:$anko_version"
點(diǎn)擊事件
java中的寫法
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
...
}
});
Kotlin中的基本寫法
button.setOnClickListener(object :View.OnClickListener{
override fun onClick(v: View?) {
...
}
})
但是可以轉(zhuǎn)化為lambda表達(dá)
button.setOnClickListener { ... }
利用Anko可以達(dá)到
button.onClick { ... }
Intent
//java
Intent intent=new Intent(this,SecondActivity.class);
//kotlin
val intent=Intent(this,SecondActivity::class.java)
//下面沒什么區(qū)別
intent.putExtra("id",666);
intent.putExtra("name","John");
startActivity(intent);
利用Anko
startActivity<SecondActivity>("id" to 666, "name" to "John")
當(dāng)然,打開瀏覽器,分享,發(fā)郵件的intent也為我們準(zhǔn)備好了
browse("https://makery.co")
share("share", "subject")
email("hello@makery.co", "Great app idea", "potato")
Toast
java/kotlin
Toast.makeText(this,"這是一個(gè)比較長(zhǎng)的toast",Toast.LENGTH_SHORT).show();
anko
toast("Hi there!")
toast(R.string.message)
longToast("Wow, such a duration")
對(duì)話框
kotlin
val builder = AlertDialog.Builder(this)
builder.setTitle("Warning")
builder.setMessage("Kotlin is so fresh!")
builder.setPositiveButton("OK") { dialog, which -> toast("Yay!") }
builder.setNegativeButton("Cancel") { dialog, which -> toast("What?") }
builder.show()
anko
alert("Kotlin is so fresh!", "Warning") {
positiveButton("確定") { toast("點(diǎn)擊了確定") }
negativeButton("取消") { toast("點(diǎn)擊了取消") }
}.show()
第一篇大概就說到這吧,下一篇我們...不好意思,沒有了。