前几天,突然想试试在android上如何启用一个app,于是经过选择,选择了kotlin语言来实现。
网上说要先安装intellij idea的环境,安装好后,按照helloworld的示例,运行出了界面。
接下来,想自己写界面,自然就会涉及到文本和按钮。然后网上很多都说使用kotlin的绑定视图技术,就可以直接在kt中编辑这些控件了。就按照网上说的引入kotlin-android-extensions,进行对应的设置,但是结果一直都报错。后来经过搜索,知道了最新的情况是,Google官方放弃了kotlin-android-extensions插件,使用ViewBinding技术来代替了。
首先,修改build.gradle文件
在android节点下增加buildFeatures 信息,
-
android {
-
...
-
buildFeatures {
-
viewBinding = true
-
}
-
}
可实际却是,viewBinding = true不生效,
使用 viewBinding后,更新后构建仍会有错误,
不经意的查看idea提示,修改为 dataBinding ,然后构建时会自动下载对应的文件,才可以正常使用kotlin的android 扩展的viewbinding。
buildFeatures { dataBinding true } 的设置才是正确的。
1、build.gradle(:app)文件如下:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.test_kotlin_empty'
compileSdk 33
defaultConfig {
applicationId "com.example.test_kotlin_empty"
minSdk 33
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
dataBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
2、kt文件如下:
package com.example.test_kotlin_empty
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.test_kotlin_empty.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.helloTv.text = "Hello Kotlin666888!"
}
}
3、activity_main.xml 文件如下:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/hello_Tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="38sp"/>
</LinearLayout>
</layout>
4、运行后的界面如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)