什么是Kotlin?
Kotlin是针对JVM、Android 和浏览器的静态编程语言!
100% 与 Java™ 可互操作!
Kotlin在Android上的使用
Kotlin可以直接将布局的id
来当成变量使用:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
if (holder is TitleHolder) {
// 分类
holder.itemView.new_item_title.text = mDatas?.get(position)?.type
} else if (holder is ContentViewHolder) {
with(holder.itemView) {
// 名称
new_item_text.text = mDatas?.get(position)?.desc
// 作者
new_item_user.text = mDatas?.get(position)?.who.let { Constant.NEW_ITEM_USER_NULL }
}
// 点击
holder.itemView?.setOnClickListener {
onClick ->
val intent = Intent(mContext, DetailActivity::class.java)
val data = Bundle()
data.putString(Constant.URL, mDatas?.get(position)?.url)
intent.putExtras(data)
mContext?.startActivity(intent)
}
}
}
Java在写Bean类的时候是这样写的1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class DataTypeBean {
private boolean error;
private List<ResultsBean> results;
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public List<ResultsBean> getResults() {
return results;
}
public void setResults(List<ResultsBean> results) {
this.results = results;
}
public static class ResultsBean { ... }
}
而在Kotlin中直接用数据类(Data Classes)写1
2
3
4
5
6
7
8
9// DataTypeBean类
data class DataTypeBean(var error: Boolean = false, var results: MutableList<ResultsBean>? = null)
// ResultsBean类
data class ResultsBean(var _id: String? = null, var createdAt: String? = null,
var desc: String? = null, var publishedAt: String? = null,
var source: String? = null, var type: String? = null,
var url: String? = null, var used: Boolean = false,
var who: String? = null, var images: MutableList<String>? = null)
是不是很方便,很简洁,下面就介绍如何安装Kotlin插件
Kotlin的插件安装
Settings->Plugins->Browse Repositories->搜索Kotlin
项目添加Kotlin(Android Studio)
已存在的项目直接转换为Kotlin
Code->Convert Java file to Kotlin file
- 转换完成后,会要求配置Kotlin
- 选择Modules和Kotlin的版本
- Sync Gradle
- 转换后的文件,会有些语法之类的错误,这个后面再说
新建项目
Project的gradle
在
buildscript
里面添加kotlin的版本,当前是1.0.41
ext.kotlin_version = '1.0.4'
在
dependencies
里面添加Kotlin依赖1
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
Module的gradle
添加
apply plugin
1
2apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'在
dependencies
添加依赖1
2compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
运行app