Android Kotlin(一)

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

    
    

    




    


    

最外层包裹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

  • Getting started with data binding
  • Data Binding Library
  • Generated Binding Classes

你可能感兴趣的:(Android Kotlin(一))