gradle 配置
Moudle:app gradle
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "top.zcwfeng.kotlin"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
//需要自己添加,对应布局文件件
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
// 需要自己添加dataBinding
dataBinding {
enabled = true
}
}
vectorDrawables.useSupportLibrary = true
对应
app:srcCompat="@drawable/empty_dice"
dataBinding 打开之后就可以不用findViewById
有点像黄油刀ButterKnife的用法
布局文件xml
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable name="myName"
type="top.zcwfeng.kotlin.bean.MyName"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/dice_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
app:srcCompat="@drawable/empty_dice"
tools:src="@drawable/dice_1"/>
<Button
android:layout_gravity="center_horizontal"
android:id="@+id/btn_kotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Kotlin"/>
</LinearLayout>
</layout>
最外层包裹layout
注意MainActivity 的一些写法
。。。
import androidx.databinding.DataBindingUtil
import top.zcwfeng.kotlin.databinding.ActivityMainBinding
。。。
class MainActivity : AppCompatActivity() {
lateinit var databinding:ActivityMainBinding//Kotlin laterinit
var myName:MyName = MyName("Alice")// Class MyName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
databinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
databinding.btnKotlin.setOnClickListener {
rollDice(it)
}
}
private fun rollDice(view: View) {
var RandomInt = Random().nextInt(6) + 1
//Kotlin-> java switch
var drawableResource = when(RandomInt){
1-> R.drawable.dice_1
2-> R.drawable.dice_2
3-> R.drawable.dice_3
4-> R.drawable.dice_4
5-> R.drawable.dice_5
else -> R.drawable.dice_6
}
// 不需要去findViewById
databinding.apply {
databinding.textName.setText("Finshy")
databinding.diceImage.setImageResource(drawableResource)
invalidateAll()
}
}
}
MyName Class:
data class MyName( var name:String="",var nickName:String="")
小结:
使用了lateinit
lateinit var A:String 不需要 var A:String? = null
使用了dataBinding:binding View bindingData
配置gradle 开关,布局加入layout包裹
使用了Kotlin 的when
定义Kotlin Class
网友评论