Android使用kotlin开发入门 (学习一)
关于
南京又是持续下雨的季节,下午在学习郭霖老师和鸿洋老师的博客文章的时候,看到了郭老师讲解的Jetpack新成员,App Startup一篇就懂,内容博大精深,发现是我还没学习使用的kotlin语言写的博客demo。。。回顾这一年来的Android工作,基本都是用的java语言写的代码,之前也看到有朋友在朋友圈分享他的kotlin写的天气类型app。现在想来是时候学习并记录一下。好在kotlin有一个特别好的优点就是可以和java混合开发,特别适合我这种kotlin新手在项目中混合编写学习。
下面的demo简单记录下如何使用kotlin编程,别的不说,代码量少了一大截。
效果图
简单演示了kotlin如何使用控件实例的点击监听。
新建一个Android项目
新建项目如下,如图所示,选择kotlin,然后点击继续即可:
等待自动生成即可。
我们看到MainActivity.kt(已经由.java变成了.kt),里面的基本代码也已经发生了变化:
其中变化之一呢,是由原来的:
public class Mainctivity extends AppCompatActivity()
变成了现在的这样:
class MainActivity : AppCompatActivity()
这就是继承,由原来的extends变成了:。
二就是override 字段,用来字类继承父类方法。
第三就是每局代码结尾不需要用;来做结尾。
第四就是定义变量类似C,用的val ,内容要赋值,不然会有空提示。
修改Activity_main.xml文件
新增对应的textview与button控件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:id="@+id/tvTestKotlin"
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" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonKotlin"
android:text="click"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
修改MainActivity.kt文件
tvTestKotlin.text="hello Kotlin World!"
添加代码,设置主界面textview实例的内容为hello Kotlin World!,其中tvTestKotlin为xml文件中的TextView的实例id。
以前java写法是:
TextView tv = (...) findViewById(R.id.tvTestKotlin)
tv.setText(hello Kotlin World!);
而现在只需要一句话即可解决。
class MainActivity : AppCompatActivity() {
var a: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
buttonKotlin.setOnClickListener(View.OnClickListener {
val intent = Intent(this,Main2Activity::class.java)
startActivity(intent)
Toast.makeText(this,"提示",Toast.LENGTH_SHORT).show()
})
tvTestKotlin.text="hello Kotlin World!"
tvTestKotlin.setOnClickListener { Toast.makeText(this,"提示",Toast.LENGTH_SHORT).show() }
tvTestKotlin.setTextColor(resources.getColor(R.color.colorPrimary))
}
}
如上代码中还有我们眼熟的.setOnClickListener();方法,以前java中一般会有两种写法:
一种是button.setOnClickListener(this);或者button.setOnClickListener(new View.OnClickListener{});但是现在kotlin中没有new 用法,即直接:
buttonKotlin.setOnClickListener(View.OnClickListener {})
或者更简单写法:
tvTestKotlin.setOnClickListener { Toast.makeText(this,"提示",Toast.LENGTH_SHORT).show() }
本篇博客就到此为止了,后续还会有kotlin的深入学习,有问题欢迎批评指教!