Android 依賴注入 ButterKnife 基本使用

來源:互聯網
上載者:User

標籤:

ButterKnife 是一個快速 Android View 注入架構,開發人員是Jake Wharton,簡單的來說,ButterKnife 是用註解的方式替代findViewById和setXXXListener

項目GitHub地址:https://github.com/JakeWharton/butterknife/

Android Studio 配置步驟可以直接參考Github上的介紹,很簡單。

ButterKnife 是在編譯時間註解,不會在運行時產生負擔,Build工程後你會發現它產生了需要的代碼,即它不是使用反射或者在運行時產生代碼,所以它不會導致任何效能問題,也不會影響應用速度。

 

看過下面這句話,使用之後發現挺有道理。

ButterKnife 不能算是一個真正的注入,更像是View的代言。

 

1. 替代findViewById()

在變數聲明的時候加上註解,如果找不到id,會在編譯時間報錯,注意View變數聲明的時候不能為private或者static。

@BindView(R.id.hello_world_tv)TextView helloWorldTv;@BindView(R.id.a_hello_world_btn)Button aHelloWorldBtn;

在setContentView(view)後設定bind()。

setContentView(R.layout.activity_main);// ButterKnife.inject(this) should be called after setContentView()ButterKnife.bind(this);

ButterKnife 同樣可以在Fragment、Adapter中使用,注意Fragment中要在onDestroyView()中調用unbind()。

public class SimpleFragment extends Fragment {    private Unbinder unbinder;    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_simple, container, false);        unbinder = ButterKnife.bind(this, view);        return view;    }    @Override    public void onDestroyView() {        unbinder.unbind();        super.onDestroyView();    }}

 

2. 設定監聽

ButterKnife 支援設定多種Listener,注意這裡的方法仍然不能是private和static

@OnClick
@OnLongClick
@OnPageChange
OnPageChange.Callback
@OnTextChanged
OnTextChanged.Callback
@OnTouch
@OnItemClick
@OnItemLongClick
@OnCheckedChanged

具體使用方法有待繼續學習。

 

3. 綁定資源

注意變數聲明同樣不能為private或者static。

    @BindString(R.string.app_name)    String appName;//sting    @BindColor(R.color.red)    int textColor;//顏色    @BindDrawable(R.mipmap.ic_launcher)    Drawable drawable;//drawble    @BindDrawable(R.drawable.selector_image)    Drawable selector;

 

4. 多個View進行統一操作

未使用,帶學習。

 

 

參考:

http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549

http://blog.csdn.net/jdsjlzx/article/details/51281844

 

待學習:

1. 常用Listener的使用

2. butterknife 源碼分析

 

Android 依賴注入 ButterKnife 基本使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.