0
点赞
收藏
分享

微信扫一扫

Kotlin学习日志(一)TextView、Button、Toast的使用


在Android Studio 中使用Kotlin编写TextView、Button、Toast

介绍的话我就不说了,可以看我的第一篇关于Kotlin的文章,讲了为什么要用Kotlin的原因,进入正题,我们现在已经重新创建了一个Kotlin的项目,我在activity_main.xml文件中放了一个id为tv_hello的TextView和一个id为btn_test的Button,
然后在MainActivity.kt中的头部导入
贴一下布局文件activity_main.xml的的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/tv_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_marginTop="20dp"
android:id="@+id/btn_test"
android:text="测试"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

import kotlinx.android.synthetic.main.activity_main.*

这句话的意思是引进Kotlin的的控件变量自动映射功能,接下来只要是这个activity_main.xml文件中的控件,我们就都不需要在调用findViewById方法来获取对象了。如下图所示

Kotlin学习日志(一)TextView、Button、Toast的使用_Kotlin入门


相信很容易看明白吧,布局文件中TextView的text属性是“Hello World!”,我们通过代码改成“你好 Kotlin”,按钮点击之后我们改变这个按钮的文本值为“您点了一下!”,当你点了以后就会变化,还有长按的代码也比较简单,我贴一下

//Button  长按事件
btn_test.setOnLongClickListener { btn_test.text = "您长按了一会儿";true }

长按则需要加一个布尔类型的返回值,刚才我们只是改变按钮的文本,接下来我们来写点击之后弹出一个Toast消息,这个比较简单,代码如下

//Button  点击事件 Toast消息提示 短消息
btn_test.setOnClickListener { toast("小提示:您点了一下") }

kotlin 的 toast方法默认的是短时显示消息,如果要长时显示消息呢?也很简单,代码如下:

//Button  点击事件 Toast消息提示  长消息
btn_test.setOnClickListener { longToast("长提示:您点了一下") }

那如果我们要在点击的同时改变按钮的文本和弹出Toast消息呢?
代码如下:

//Button  点击事件 改变按钮文本并弹出Toast消息
btn_test.setOnClickListener { btn_test.text = "您点了一下!";toast("小提示:您点了一下") }

该说的都说完了,我再介绍一个库:Anko库
简介:Anko是使用Kotlin语言编写的一个Android增强库,它用于简化Android开发时的Kotlin代码,让你的Kotlin代码更加的简洁易懂,就如同我们刚才用到的toastlongToast,这两个函数再Anko库中的原始定义是下面这样的:

toast

fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

longToast

fun Context.longToast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()

注意到Anko库的Toasts.kt文件是给Context类添加了扩展函数toast和longToast,这意味着凡是继承了Context的类(包括Activity、Service等),均可在类内部代码直接调用toast和longToast方法实现消息提示。为了正常使用toast和longToast,我们需要在项目的build.gradle,在buildscript节点中补充下面一行代码,

ext.anko_version = '0.9'//指定Anko的版本

当然也可能有更高的版本,目前先用0.9,如下图所示

Kotlin学习日志(一)TextView、Button、Toast的使用_android_02


同时,在模块的build.gradle,在dependencies节点中补充anko-common包如下代码:

implementation"org.jetbrains.anko:anko-common:$anko_version"

如下图所示

Kotlin学习日志(一)TextView、Button、Toast的使用_android_03


OK,就是这样,我觉得你们也可以从后往前看,待续。。。

​​Kotlin学习日志(二)数据类型​​​​Kotlin学习日志(三)控制语句​​​​Kotlin学习日志(四)函数​​​​Kotlin学习日志 (五)类与对象​​


举报

相关推荐

0 条评论