_androidstudio kotlin android ">
当前位置:   article > 正文

Android Stdio引入kotlin-android-extensions插件_androidstudio kotlin android extensions

androidstudio kotlin android extensions

在Activity中使用Toast

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <Button
  6. android:id="@+id/button1"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="Button 1"/>
  10. </LinearLayout>
  1. class FirstActivity : AppCompatActivity() {
  2. override fun onCreate(savedInstanceState: Bundle?) {
  3. super.onCreate(savedInstanceState)
  4. setContentView(R.layout.first_layout)
  5. val button1 : Button = findViewById(R.id.button1)
  6. button1.setOnClickListener {
  7. Toast.makeText(this,"You clicked Button 1",Toast.LENGTH_SHORT).show()
  8. }
  9. }

在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快捷键,程序会自动导入相关设置的。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/247027
推荐阅读
相关标签