转自 :http://blog.csdn.net/yianemail/article/details/53114630
一:介绍
Kotlin是由JetBrains设计的开放源码的编程语言,它正在Java开发者中变得越来越流行。Kotlin通常被吹捧为Java的继承者,相比较Java而言,Kotlin提供更为丰富的开发经验,因为它更现代,更具表现力和更简介。
如果你在寻求Android开发的可替代编程语言,那么应该试一下Kotlin。使用Kotlin,你可以很容易的在Android工程中替代Java或者与Java混合使用。
本文接下来将介绍在Android Studio工程中如何使用Kotlin .
Kotlin : https://kotlinlang.org/
二:Kotlin Studio 集成
app/build.gradle
apply plugin: 'com.android.application'
//add kotlin plugin
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.example.huanjulu.kotlinsource"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
//...
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
repositories {
mavenCentral()
}
project/build.gradle
// Top-level build file where you can add configuration options common to allsub-projects/modules.
buildscript {
ext.kotlin_version = '1.0.5'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
三:代码实例
MainActivity.kt
/**
* Created by huanjulu on 16/11/9.
*/
class MainActivity :AppCompatActivity(), UserSessionContract.UserSessionView {
var mPresenter: UserSessionContract.UserSessionPresenter? =null
//Adapter
var adapter: Adapter = Adapter(this)
//实例化LinearLayoutManager
var linearlayout = LinearLayoutManager(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//start 订阅
UserSessionPresenter(this).subscribe()
mPresenter!!.dataP(null)
//设置adapter 以及 layoutManager
recycleview.adapter = adapter
recycleview.layoutManager = linearlayout
}
override fun onDestroy() {
super.onDestroy()
//cancle 订阅
mPresenter!!.unSubscribe()
}
override fun <T> dataV(t: T?) {
t as List<String>
//非空调用
adapter!!.load(t)
}
override fun setPresenter(p: UserSessionContract.UserSessionPresenter) {
this.mPresenter = p
}
}
- 其中的remote data 模拟了一些网络数据
UserSessionRemoteImpl.kt
/**
* Created by huanjulu on 16/11/9.
*/
class UserSessionRemoteImpl : UserSessionRemote {
var data: List<UserSessionWrap> = listOf(UserSessionWrap(), UserSessionWrap(), UserSessionWrap(), UserSessionWrap(), UserSessionWrap(), UserSessionWrap())
var datas: List<String> = listOf(
"稀土攫金"
, "泡在网上的日子",
"cokk","V2ex",
"开发头条",
"23code"
)
override fun <T> dataRemote(t: T?): List<String> {
data.forEach {
}
return datas
}
}
Adapter.kt
/**
* Created by huanjulu on 16/11/9.
*/
class Adapter constructor(context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val mContext: Context?
companion object {
}
init {
this.mContext = context
}
val items = LinkedList<String>()
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
(holder as ViewHolder).bind(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_data, parent, false)
return ViewHolder(view)
}
fun load(articles: List<String>) {
if (articles.isNotEmpty()) {
items.run {
clear()
addAll(articles)
notifyDataSetChanged()
}
}
}
override fun getItemCount(): Int = items.size
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(item: String) {
view.run {
tag = this
Log.d("TAG", item)
content.text = item
}
}
}
}
效果
四:结语
在使用完Kotlin之后,
- 干净整洁,代码量少了一半左右
- 类型推断,扩展方法
- when while if 表达式更加方便
- 和JAVA调用很方便,能直接使用原有的JAVA方法
- 是它可以配合ANKO(虽然ANKO现在还不支持JAVA8)),从此告别XML布局