Before java has been used to develop Android projects, learning a new language kotlin, try to come and talk about some of the features Android kotlin enhancements
Create a project
I'm using Android Studio3.0 +, so by default to support kotlin
Remember when creating a project supported by checking kotlin
Find examples provided listeners
We are ever found by findviewbyid example, while kotlin provides a more efficient way, only one line of code, then we can use various examples directly define the layout of the inside of the
As usual, we can use an instance to change the contents of the control, at the same time, this button can also be used as judge listener.
We used the click listener, use a switch or if statement to determine control of clicks to perform different operations. And kotlin used directly determining instances, specific code in the following MainActivity.java
switch(v.getId){
case R.id.btn:
//逻辑操作
break;
}
if(v.getId == R.id.btn){
//逻辑操作
}
activity_main.xml
<?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="com.wan.noveldownloader.activity.MainActivity">
<Button
android:id="@+id/btn_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.wan.noveldownloader.activity
import android.os.Bundle
import android.view.View
import com.wan.noveldownloader.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : BaseActivity(),View.OnClickListener {
override fun onClick(v: View?) {
when (v) {
//操作
btn_test -> showToast("htllo")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//这里的btn_test就是布局文件的按钮实例
//输入btn_test会自动增加一行import kotlinx.android.synthetic.main.activity_main.*
btn_test.setOnClickListener(this)
}
}