1. 程式人生 > >Android - Butterknife

Android - Butterknife

概述

ButterKnife是一個專專注於Android系統的View注入框架,使用ButterKnife對效能基本沒有損失,因為ButterKnife用到的註解並不是在執行時反射的,而是在編譯的時候生成新的class.

ButterKnife的註冊與繫結

1、在Activity中繫結ButterKnife

由於每次都要在Activity中的onCreate繫結Activity,所以個人建議寫一個BaesActivity完成繫結,子類繼承即可。繫結Activity必須在setContentView之後。使用ButterKnife.bind(this)進行繫結。

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

2、在Fragment中繫結ButterKnife

Fragment的生命週期不同於activity,在onCreateView中繫結一個Fragment時,在onDestroyView中將檢視設定為null。當你呼叫bind來為你繫結一個Fragment時,ButterKnife會返回一個Unbinder例項,在適當的生命週期(onDestroyView)回撥中呼叫它的unbind方法進行Fragment解綁。

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();  
    }  
}

3、在Adapter中繫結ButterKnife

在Adapter的ViewHolder中使用,將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);  
      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的基本使用

1、繫結View

(1)控制元件id註解:@BindView

@BindView( R2.id.button)  
public Button button;

(2)佈局內多個控制元件id註解:@BindViews

public class MainActivity extends AppCompatActivity {  

    @BindViews({ R2.id.button1, R2.id.button2,  R2.id.button3})  
    public List<Button> buttonList ;  

    @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 ");  
    }  
} 

2、繫結資源

(1)繫結string字串:@BindString

public class MainActivity extends AppCompatActivity {  

    @BindView(R2.id.button) //繫結button 控制元件  
    public Button button ;  

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

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        //繫結activity  
        ButterKnife.bind( this ) ;  
        button.setText( str );  
    }  
} 

(2)繫結string裡面的array陣列 @BindArray

<resources>  
    <string name="app_name">城市</string>  

    <string-array name="city">  
        <item>北京市</item>  
        <item>天津市</item>  
        <item>哈爾濱市</item>  
        <item>大連市</item>  
        <item>香港市</item>  
    </string-array>  

</resources>  

------------------------------------------------------------------------------

public class MainActivity  extends AppCompatActivity {  

    @BindView(R2.id.button) //繫結button 控制元件  
    public Button button ;  

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

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

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        //繫結activity  
        ButterKnife.bind( this ) ;  
        button.setText(citys[0]);  
    }  
}

(3)繫結Bitmap資源 @BindBitmap

public class MainActivity extends AppCompatActivity {  

    @BindView( R2.id.imageView ) //繫結ImageView 控制元件  
    public ImageView imageView ;  

    @BindBitmap( R2.mipmap.bm)//繫結Bitmap 資源  
    public Bitmap bitmap ;  

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

        //繫結activity  
        ButterKnife.bind( this ) ;  

        imageView.setImageBitmap(bitmap);  
    }  

} 

(4)繫結一個顏色值 @BindColor

public class MainActivity extends AppCompatActivity {  

    @BindView( R2.id.button)  //繫結一個控制元件  
    public Button button;  

    @BindColor( R2.color.colorAccent ) //具體色值在color檔案中  
    int black ;  //繫結一個顏色值  

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

        //繫結activity  
        ButterKnife.bind( this ) ;  

        button.setTextColor(  black );  
    }  
}

3、事件繫結

(1)繫結點選事件

public class MainActivity extends AppCompatActivity {  

    @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 ;  
    }  

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

        //繫結activity  
        ButterKnife.bind( this ) ;  
    }  
}

(2)指定多個id繫結事件

public class MainActivity extends AppCompatActivity {  

    //Tip:當涉及繫結多個id事件時,我們可以使用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;  
        }  
    }  

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

        //繫結activity  
        ButterKnife.bind( this ) ;  
    }  
}

通過上面的例子可以看出多條點選事件是沒法有用R2的方式,如果一定要使用R2的寫法,可以單一逐次寫:

public class MainActivity extends AppCompatActivity {    

    @OnClick(R2.id.ll_product_name)    
    public void onViewClicked1(View view) {    
       System.out.print("我是點選事件1");               
    }    
    @OnClick(R2.id.ll_product_lilv)    
    public void onViewClicked2(View view) {    
       System.out.print("我是點選事件2");     
    }   
    @OnClick(R2.id.ll_product_qixian)    
    public void onViewClicked3(View view) {    
       System.out.print("我是點選事件3");               
    }    
    @OnClick(R2.id.ll_product_repayment_methods)    
    public void onViewClicked4(View view) {    
       System.out.print("我是點選事件4");               
    }    

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

        //繫結activity    
        ButterKnife.bind( this ) ;    
    }    
}

(3)自定義View使用繫結事件

不用指定id,直接註解OnClick。

public class MyButton extends Button {  
  @OnClick  
  public void onClick() {}  
}