Butterknife 是Android Studio 的一个快速开发的插件这个开源库可以让我们简化大量的findViewById()和setonclicktListener(),其对性能的影响微乎其微(查看过Butter Knife的源码,其自定义注解的实现都是限定为RetentionPolicy.CLASS,也就是到编译出.class文件为止有效,在运行时不额外消耗性能,其是通过java注解自动生成java代码的形式来完成工作。
1 安装
1. 点击File选择Settings..
2. 点击Plugins 搜索Butterknife,然后点击Search in repostiitories
3.搜索Butterknife,在弹出的选择框里选择第一个,点击Install进行安装
4.安装完成后,点击Restart Android Studio,然后点击OK
点击重启Android Studio,到这里插件安装完毕
2 使用
在项目的bulid.gradle中添加依赖
compile 'com.jakewharton:butterknife:7.0.1'
数字代表版本,可以是别的版本,然后点击Sync Now 如下图所示
重新编译一下该项目,就可以在代码中使用注解的方式了,我们先写一个简单的布局文件来举例
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@color/blue"
android:gravity="center"
android:text="textview1"
android:textColor="@color/white"
android:textSize="18dp" />
<Button
android:id="@+id/bt_share"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="@color/blue"
android:gravity="center"
android:text="按钮1"
android:textColor="@color/white"
android:textSize="18dp" />
<Button
android:id="@+id/bt_login"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:background="@color/blue"
android:gravity="center"
android:text="按钮2"
android:textColor="@color/white"
android:textSize="18dp" />
</LinearLayout>
代码里的简单使用
点击Confirm后会自动生成如下代码
本文使用的As版本为2.2