写在开头
接触Kotlin有一段时间了,以前只是当作兴趣来看看,今天看到Google I/O大会,Kotlin作为Android官方开发语言,不免有一种突然转正的感觉,在这感谢入门领路人:微信号KotlinX
效果图
1:环境配置
android studio加入Kotlin插件
2:打包依赖
3:开发
1.Kotlin代码,这里是用Anko写的布局,Anko也是JetBrains开发的库
import android.content.Context
import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import demo.kotlin.myapplication.Java.MainActivity
import demo.kotlin.myapplication.R
import org.jetbrains.anko.*
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Anko加载布局方式
Main2ActivityUI(this).setContentView(this)
}
class Main2ActivityUI(activity: Context) : AnkoComponent<Main2Activity> {
var activity = activity
override fun createView(ui: AnkoContext<Main2Activity>) = with(ui) {
verticalLayout {
padding = dip(30)
var title = editText {
id = R.id.todo_title
hintResource = R.string.title_hint
textColor = Color.BLUE
}
var desc = editText {
id = R.id.todo_desc
hintResource = R.string.description_hint
}
button {
id = R.id.todo_add
textResource = R.string.add_todo
onClick { view -> createTodoFrom(activity, title, desc) }
}
}
}
/**
* 点击事件,调用java的Activity并传递数据
*/
private fun createTodoFrom(activity: Context, title: EditText, desc: EditText) {
activity.startActivity<MainActivity>("title" to "账号:" + title.text.toString() + "--密码:" + desc.text.toString())
}
}
}
2.Java代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String title = getIntent().getExtras().getString("title");
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(title);
}
}
---------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="demo.kotlin.myapplication.Java.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>