Android:一键find控件,今后告别繁琐的findViewById



记得以前写过一篇博客叫作:





你还在苦逼地findViewById吗?使用ButterKnife今后轻松定义控件
此文是介绍在eclipse环境下使用ButterKnife的,相比传统的findViewById确实简单了点~可是笔者认为还不够简单~~
在谷歌中止对ADT+Eclipse中止更新以后~笔者还苦苦在Eclipse坚持了几个月终于开始转移到Android Studio上撸代码~~
所以本文也是在Android Studio基础上写的,若是有用Eclipse能够参考:
你还在苦逼地findViewById吗?使用ButterKnife今后轻松定义控件


ButterKnife简介



前面的文章已经介绍过了这里不介绍了!!!


ButterKnife+Android ButterKnife Zelezny组合

目前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----->完成~

好了到此为止就完成了。
下面咱们来具体看看ButterKnife有多方便:
为了演示绑定控件,笔者写了几个控件:
<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/testTextId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/testBtnId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/testetId"
        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




就这样把全部控件"find"出来了~~只不过是经过注解的方式find出来的(笔者在前面的博客也介绍过注解,有兴趣的能够去看看)~~是否是好方便呢?虽然没有标题所说那样“一键”搞定可是~随便点两下就可以把之前写半天才find完的控件一会儿“find”出来了~是否是以为好爽~~