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”出來了~是不是覺得好爽~~





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章