[Android Basics] Kotlin peut appeler le contrôle d'interface utilisateur correspondant sans appeler findViewById

Kotlin n'a pas besoin de findViewById

Nous écrivons souvent du code Android et avons souvent besoin de trouver l'identifiant, par exemple, 10 boutons doivent être appelés 10 foisfindViewById

Ce problème n'existe plus en kotlin, le projet Android écrit en Kotlin est app/build.gradleréférencé dans le fichier comme suit :

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {

    buildFeatures {
        prefab true
    }
}

Ce plugin générera automatiquement une variable du même nom en fonction de l'identifiant de contrôle défini dans le fichier du layout, qui peut être utilisé directement dans l'activité sans appeler findViewById()

Par exemple, il y a un bouton1 dans le layout

<?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>

Ensuite, vous pouvez appeler button1 via la liaison

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.brooks.activitytest.databinding.FirstLayoutBinding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.title.view.*


class FirstActivity : AppCompatActivity() {
    
    
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        val binding = FirstLayoutBinding.inflate(layoutInflater)	// 通过binding就可以调用其他button了
        setContentView(binding.root)
        //binding.button1.setOnClickListener {
    
    
          //  Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
        //}
        button1.setOnClickListener {
    
    
          Toast.makeText(this, "You clicked Button 1", Toast.LENGTH_SHORT).show()
       }
    }
}

import kotlinx.android.synthetic.main.activity_main.*Et import kotlinx.android.synthetic.main.title.view.*vous pouvez contrôler directement le contrôle via l'identifiant ! ! !

Guess you like

Origin blog.csdn.net/myt2000/article/details/126620845