一步步学习kotlin for android(三) kotlin省略findviewById

本文介绍如何利用Kotlin简化Android开发中的视图绑定过程,通过引入特定插件及语法,实现更简洁高效的代码编写方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

findViewById      今天的内容涉及到findViewByID,android语言原来这个特别繁琐,现在好了,kotlin语言,直接拿来布局里面的id用,省去好多重复工作量啊

在使用kotlin的id之前,需要先在builde.gradle里引入这个

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'

    defaultConfig {
        applicationId ""
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 45
        versionName "4.2.0"
    }
加入黄色字体部分

然后再在activity里面引入:

import kotlinx.android.synthetic.main.activity_start.*
其中,activity_start就是你的布局文件的名称,*代表布局里所有的id

接着就可以直接使用布局里面的id了,例如:

<ImageView
    android:id="@+id/img"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:contentDescription="@null"
    android:scaleType="fitXY"
    android:src="@mipmap/bg_home" />

<TextView
    android:id="@+id/timecount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_margin="@dimen/spacing_small"
    android:text="3"
    android:textColor="@color/normal"
    android:textSize="@dimen/font_large"
    android:visibility="gone"/>

在activity里不需要做任何其他查找,直接使用

img.setBackgroundColor(resources.getColor(R.color.background));

getResources().getColor(R.color.background));成了
resources.getColor(R.color.background));

timecount.text="我是kotlin";


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值