使用butterknife轻松定义控件
来源:互联网 发布:centos ssh 连不上 编辑:程序博客网 时间:2024/05/18 00:24
你还在使用findviewbyid么?使用butterknife轻松定义控件
ButterKnife简介
从大量的findViewById()和setonclicktListener()解放出来,其对性能的影响微乎其微(查看过Butter Knife的源码,其自定义注解的实现都是限定为RetentionPolicy.CLASS,也就是到编译出.class文件为止有效,在运行时不额外消耗性能,其是通过java注解自动生成java代码的形式来完成工作),其也有一个明显的缺点,那就是代码的可读性差一些,但了解了之后,上手也很快。。。
目前ButterKnife的最新版本是7.0.1
用法:
首先在项目的build.gradle文件中添加一句话:
compile 'com.jakewharton:butterknife:7.0.1' 然后点击右上角的sync now,android studio就会自动下载ButterKnife
要想达到一键绑定控件的效果还需要安装Android ButterKnife Zelezny插件,
打开Android Studio设置面板—>Plugins—->可以看到有个搜索框我们输入ButterKnife—–>然后点击下面的Browse Repositories—->选择Android ButterKnife Zelezny—->安装—>重启Android Studio—–>完成
为了演示绑定控件,写了几个控件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ImageView android:id="@+id/testImageId" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/edit" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
传统做法我们是在Activity上一个个find出来,就只有这几个控件还好,但是我们写程序的时候有些界面远远不止这几个控件~~难道我们就一个个地find出来吗?
看过布局文件我们回到Activity.java
首先在setContentView(XXX)的括号内容右击:
选择Generate:
选择Generate ButterKnife Injections:
到这里可以看到列出了当前布局文件可以被find出来的控件,如果不需要再.java文件使用的控件可以不勾上,默认情况下控件命名与布局里的id名称一致。
我们再看左下角有一个Create ViewHolder,可以知道,ButterKnife也可以用在创建ViewHolder上,这里不再详述,接下来我们点击Confirm
这样就可以将所有界面上带有id属性的空间全部找出来而不是find出来的
注:一定要在oncreat里边加上初始化
- 使用butterknife轻松定义控件
- 你还在苦逼地findViewById吗?使用ButterKnife从此轻松定义控件
- 使用ButterKnife自动化绑定控件
- #android 拾遗07--使用butterknife绑定控件
- android 使用butterknife简化加载布局控件
- ButterKnife使用
- butterknife使用
- ButterKnife使用
- 使用butterknife
- ButterKnife使用
- butterknife使用
- ButterKnife使用
- butterknife使用
- ButterKnife使用
- ButterKnife使用
- ButterKnife使用
- ButterKnife使用
- ButterKnife使用
- Intersection CodeForces - 21B(最大公约数gcd)
- 第五篇:赔率和盘口的特征之二
- 事务控制和锁定语句
- React-native 布局
- Android Studio 上传SVN忽略文件
- 使用butterknife轻松定义控件
- CCF 201612-4 压缩编码 区间dp(石子合并)+四边形不等式优化
- netty5.0的任务线程无法回收的问题
- IMP-00010: not a valid export file, header failed verification
- [CSAPP] 存储器层次结构(一)
- 知识图谱
- windows环境下安装selenium
- find the nth digit HDU - 1597
- 适配器模式(Adapter):类适配器、对象适配器