在Activity中使用Toast
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"/>
</LinearLayout>
class FirstActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first_layout)
val button1 : Button = findViewById(R.id.button1)
button1.setOnClickListener {
Toast.makeText(this,"You clicked Button 1",Toast.LENGTH_SHORT).show()
}
}
在Activity中,可以通过findViewById()方法获取在布局文件中定义的元素,如上面代码,此处传入R.id.button1得到按钮的实例。findViewById()方法返回的是一个继承自View的泛型对象,kotlin无法自动推导出它是一个Button还是其他控件,此处需要将button1显示地声明成Button类型。得到该按钮的实例之后,再通过调用setOnClickListener()方法为按钮注册一个监听器,点击该按钮时就会执行监听器中的onClick()方法。
以上是只有一个按钮,可以调用findViewById()方法,但是如果布局文件中有10个控件呢,那需要调用10次该方法,而kotlin-android-extensions插件会根据布局文件中定义的控件id自动生成一个具有相同名称的变量,可以在Activity里直接使用这个变量,而不再调用findViewById()方法。
在Android Studio4.1以前我们新建kotlin项目ide会自动给我们引入该插件的引用,但是4.1以后就不再默认引入了,这个时候如果想再使用该插件,需要手动引入。
1、首先在项目的build.gradle中添加
2、接着是app中的build.gradle中添加
这个时候就不再需要使用findViewById()方法了
button1 按Alt+Enter快捷键,程序会自动导入相关设置的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)