1. 程式人生 > >Butterknife整合到應用全部方法(完整版)

Butterknife整合到應用全部方法(完整版)

整合分為了兩部分:

①僅僅在App主工程使用:

在App的 build.gradle 中新增如下程式碼:

dependencies {
  implementation 'com.jakewharton:butterknife:8.8.1'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

②如果在Library projects中使用:

在Project的 build.gradle 中新增如下程式碼:

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
  }
}

library的build.gradle中新增如下:

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'

library中使用需要使用R2,如下:

class MainActivity extends Activity {
  @BindView(R2.id.user) 
    EditText username;
  @BindView(R2.id.pass) 
    EditText password;

}

ButterKnife 注意事項:

  • 在Activity 類中繫結 :ButterKnife.bind(this);必須在setContentView();之後繫結;且父類bind繫結後,子類不需要再bind。
  • 在非Activity 類(eg:Fragment、ViewHold)中繫結: ButterKnife.bind(this,view);這裡的this不能替換成getActivity()。
  • 在Activity中不需要做解綁操作,在Fragment 中必須在onDestroyView()中做解綁操作。
  • 使用ButterKnife修飾的方法和控制元件,不能用private or static 修飾,否則會報錯。錯誤: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)
  • setContentView()不能通過註解實現。(其他的有些註解框架可以)
  • 使用Activity為根檢視繫結任意物件時,如果你使用類似MVC的設計模式你可以在Activity 呼叫ButterKnife.bind(this, activity),來繫結Controller。
  • 使用ButterKnife.bind(this,view)繫結一個view的子節點欄位。如果你在子View的佈局裡或者自定義view的構造方法裡 使用了inflate,你可以立刻呼叫此方法。或者,從XML inflate來的自定義view型別可以在onFinishInflate回撥方法中使用它。

在Activity中繫結ButterKnife:

public class MainActivity extends AppCompatActivity{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        //繫結初始化ButterKnife 必須在setContentView之後呼叫
        ButterKnife.bind(this); 
    }
}

在Fragment中繫結ButterKnife:

public class ButterknifeFragment extends Fragment{ 

    private Unbinder unbinder; 
    
    @Override 
    public View onCreateView(LayoutInflater inflater, 
                            ViewGroup container, 
                            Bundle savedInstanceState) { 

        View view = inflater.inflate(R.layout.fragment, container, false); 
        //返回一個Unbinder值(進行解綁),注意這裡的this不能使用getActivity() 
        unbinder = ButterKnife.bind(this, view); 
        return view;
    } 


    /** * onDestroyView中進行解綁操作 */ 

     @Override 
     public void onDestroyView() { 
        super.onDestroyView(); 
        unbinder.unbind(); 

     } 

}

在Adapter中繫結ButterKnife:

將ViewHolder加一個構造方法,在new ViewHolder的時候把view傳遞進去。使用ButterKnife.bind(this, view)進行繫結。

public class MyAdapter extends BaseAdapter { 

    @Override 
    public View getView(int position, View view, ViewGroup parent) { 

        ViewHolder holder; 

        if (view != null) { 
            holder = (ViewHolder) view.getTag(); 
        } else { 
            view = inflater.inflate(R.layout.testlayout, parent, false);

            // 將ViewHolder加一個構造方法,在new ViewHolder的時候把view傳遞進去
            holder = new ViewHolder(view); 
            view.setTag(holder); 
        } 
        holder.name.setText("Donkor"); 
        holder.job.setText("Android"); 

        // etc... 
        return view; 
    } 

    static class ViewHolder { 

        @BindView(R.id.title) 
        TextView name; 
        @BindView(R.id.job) 
        TextView job; 
        public ViewHolder(View view) { 
            // 使用ButterKnife.bind(this, view)進行繫結
            ButterKnife.bind(this, view); 
        } 
    } 
}

ButterKnife的基本使用

/**
* 主App工程使用如下
*/
@BindView(R.id.txt_tips)
TextView mTxtTips;

/**
* library工程使用如下
*/
@BindView( R2.id.button)  
Button button; 


// 就是R和R2的區別,因為library中目前不能呼叫R檔案了。

// 同時繫結多個
@BindViews({ R2.id.button1, R2.id.button2, R2.id.button3}) 
public List<Button> buttonList ; 

//繫結資原始檔中string字串  
@BindString(R2.string.app_name)  
 String str;  

//繫結資原始檔中string裡面array陣列  
@BindArray(R2.array.city)  
 String [] citys ;  

//繫結Bitmap 資源  
@BindBitmap( R2.mipmap.bm)
 public Bitmap bitmap ; 
 
//具體色值在color檔案中  
@BindColor( R2.color.colorAccent ) 
 int black; //繫結一個顏色值 


@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);

    ButterKnife.bind(this); 

    buttonList.get( 0 ).setText( "hello 1 "); 
    buttonList.get( 1 ).setText( "hello 2 "); 
    buttonList.get( 2 ).setText( "hello 3 "); 

    button.setText( str );
    button.setText(citys[0]);
    imageView.setImageBitmap(bitmap);
    button.setTextColor(black);  

}

@OnClick(R2.id.button1 ) //給 button1 設定一個點選事件 
public void showToast(){ 
    Toast.makeText(this, "is a click", Toast.LENGTH_SHORT).show(); 
} 
@OnLongClick( R2.id.button1 ) //給 button1 設定一個長按事件 
public boolean showToast2(){ 
    Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();
    return true ;
}

// 我們可以使用 Android studio 的 Butterknife 外掛zelezny 快速生成

@OnClick({R.id.ll_product_name, R.id.ll_product_lilv, R.id.ll_product_qixian, R.id.ll_product_repayment_methods}) 
public void onViewClicked(View view) {
 
    switch (view.getId()) { 
        case R.id.ll_product_name: 
            System.out.print("我是點選事件1"); 
            break;
        case R.id.ll_product_lilv: 
            System.out.print("我是點選事件2"); 
            break; 
        case R.id.ll_product_qixian: 
            System.out.print("我是點選事件3"); 
            break; 
        case R.id.ll_product_repayment_methods: 
            System.out.print("我是點選事件4"); 
            break; 
    }
 
}

更多註解

  • @BindView—->繫結一個view;id為一個view 變數
  • @BindViews —-> 繫結多個view;id為一個view的list變數
  • @BindArray—-> 繫結string裡面array陣列;@BindArray(R.array.city ) String[] citys ;
  • @BindBitmap—->繫結圖片資源為Bitmap;@BindBitmap( R.mipmap.wifi ) Bitmap bitmap;
  • @BindBool —->繫結boolean值
  • @BindColor —->繫結color;@BindColor(R.color.colorAccent) int black;
  • @BindDimen —->繫結Dimen;@BindDimen(R.dimen.borth_width) int mBorderWidth;
  • @BindDrawable —-> 繫結Drawable;@BindDrawable(R.drawable.test_pic) Drawable mTestPic;
  • @BindFloat —->繫結float
  • @BindInt —->繫結int
  • @BindString —->繫結一個String id為一個String變數;@BindString( R.string.app_name ) String meg;

更多事件

  • @OnClick—->點選事件
  • @OnCheckedChanged —->選中,取消選中
  • @OnEditorAction —->軟鍵盤的功能鍵
  • @OnFocusChange —->焦點改變
  • @OnItemClick item—->被點選(注意這裡有坑,如果item裡面有Button等這些有點選的控制元件事件的,需要設定這些控制元件屬性focusable為false)
  • @OnItemLongClick item—->長按(返回真可以攔截onItemClick)
  • @OnItemSelected —->item被選擇事件
  • @OnLongClick —->長按事件
  • @OnPageChange —->頁面改變事件
  • @OnTextChanged —->EditText裡面的文字變化事件
  • @OnTouch —->觸控事件
  • @Optional —->選擇性注入,如果當前物件不存在,就會丟擲一個異常,為了壓制這個異常,可以在變數或者方法上加入一下註解,讓注入變成選擇性的,如果目標View存在,則注入, 不存在,則什麼事情都不做

ButterKnife的程式碼混淆

-keep class butterknife.** { *; } 
-dontwarn butterknife.internal.** 
-keep class **$$ViewBinder { *; } 

-keepclasseswithmembernames class * {
     @butterknife.* <fields>;
} 
-keepclasseswithmembernames class * {
     @butterknife.* <methods>;
}

Butterknife外掛:zelezny

安裝完成外掛後,會提示重啟AS。重啟完後,可以寫一個佈局並且新建一個程式碼類測試下。

要注意的是,需要將游標移到setContentView(R.layout.acty_login),中的R.layout.acty_login,然後右鍵Generate就有了。