前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin View Binding,findViewById() 终结者

Kotlin View Binding,findViewById() 终结者

作者头像
码脑
发布2019-04-11 15:12:18
1.4K0
发布2019-04-11 15:12:18
举报
文章被收录于专栏:大前端

AS 中如何配置 View Binding

仅需 2 步,简单快速:

1. 配置依赖

安卓扩展是 IntelliJ IDEA 与 Android Studio 的 Kotlin 插件的组成之一,因此不需要再单独安装额外插件。

开发者仅需要在 项目根目录 → app → build.gradle 文件中启用 Gradle 安卓扩展插件即可:

代码语言:javascript
复制
apply plugin:'kotlin-android-extensions'
2. 导入合成属性

Activity内仅需要一行即可非常方便导入指定布局文件中所有控件属性:

代码语言:javascript
复制
import kotlinx.android.synthetic.main.<布局>.*

假设当前布局文件是 activity_main.xml,我们只需要引入

代码语言:javascript
复制
kotlinx.android.synthetic.main.activity_main.*。

若需要调用 View 的合成属性,同时还应该导入

代码语言:javascript
复制
kotlinx.android.synthetic.main.activity_main.view.*。

导入完成后即可调用在xml文件中以视图控件命名属性的对应扩展!


使用实例

1. lauout文件中布局TextView组件
代码语言:javascript
复制
<TextView

    android:id="@+id/hello"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"/>
2. Activity中调用对象并重新赋值
代码语言:javascript
复制
hello.text = "Hello World!"
3. 运行结果

国际惯例

贴上完整源码

完整 Layout.xml
代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#333333"/>

</LinearLayout>
完整 Activity.kt
代码语言:javascript
复制
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_find_view_binding.*

/**
 * @des Kotlin View Binding 实例类
 * @author liyongli 20190301
 * */
class FindViewBindingActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_find_view_binding)

        // 可通过 TextView 的 id 直接赋值
        hello.text = "Hello World!"

    }
}

本篇到此完结,更多 Kotlin For Android Development 内容持续更新中~

期待您点击关注或点击头像浏览更多移动端开发技术干货

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.12.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • AS 中如何配置 View Binding
  • 使用实例
  • 国际惯例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档