1. 程式人生 > >ButterKnife 簡單整合

ButterKnife 簡單整合

       ButterKnife,俗稱黃油刀,是Android的一種View依賴註解框架。View註解框架的作用就是大量節省掉去寫findViewById或者是點選操作之類的介面相關的處理程式碼。一般來說MVVM架構的專案,View註解會選用更為主流的databinding註解框架來配合,但是如果專案是MVP的架構,多會使用ButterKnife作為View的註解框架。

整合黃油刀的步奏如下:

1.app的build.gradle匯入:

implementation 'com.jakewharton:butterknife:8.5.1'           //Butterknife  黃油刀
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

2.project的build.gradle匯入: classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.2'

    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        
        //add  for butterknife
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

3. 介面中繫結黃油刀

    bind = ButterKnife.bind(this);

     成功的話會在build檔案下找到黃油刀自動生成的檔案,命名方式是介面檔案的名字後+_ViewBinding,下圖中的MainActivity_ViewBinding就是生成的檔案:

    常用的註解可以參照https://blog.csdn.net/u012527802/article/details/81059568,已經很詳細了,比如根據id繫結view的註解方式:

 @BindView(R.id.tv_location)
    TextView tv_location;




 //使用
 tv_location.setText(bean.getLat()+","+bean.getLon());