1
0
Fork 0
NotesUESTC/Android开发笔记/Kotlin findViewById用法和省略方法.md

62 lines
1.6 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# Kotlin 操作Layout控件
在Android Acitivity开发中传统的java开发中findviewbyid。在kotlin中有两种写法都可以操作layout控件。
## 一、传统写法(不推荐)
不推荐的原因主要是麻烦满屏幕都是findViewById非常的繁琐。
```kotlin
package com.geek.motion
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textView = findViewById<TextView>(R.id.textView)
textView.setText("Hello Kotlin")
}
}
```
## 二、省略写法(推荐)
下面采用的是省略写法注意需要引入import kotlinx.android.synthetic.main.activity_main.*
```kotlin
package com.geek.motion
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView.text = "Hello kotlin"
}
}
```
如果在引用import kotlinx.android.synthetic.main.activity_main.*时报错注意在build.gradle中添加**'kotlin-android-extensions'**
```shell
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
// 添加
id 'kotlin-android-extensions'
}
android {
compileSdk 32
...
```