厭煩了寫findViewById 試試ButterKnife吧,butterknife

來源:互聯網
上載者:User

厭煩了寫findViewById 試試ButterKnife吧,butterknife

先上官網

http://jakewharton.github.io/butterknife/  和 https://github.com/JakeWharton/butterknife

配置開發環境

在代碼開始之前 先要將庫加入依賴

Eclipse 

去官網手工下載 jar 包, 放到 libs目錄 或者其他方式加入到 Build Path當中

Android StudioGUI 操作的方式 

菜單上 File -> Project Structure (或者直接點工具列上的Project Structure) -> 左側 Modules下的 app  -> 右側  Dependencies 標籤頁 -> +號 -> Library dependency  搜尋 butterknife  選擇 com.jakewharton:butterknife:8.4.0 然後 OK, 版本號碼會變 , 反正選擇沒有 -compiler 這種帶尾巴的。

新的butterknife 增加了 annotationProcessor 這種方式無法添加, 所以最終還是要編輯 Gradle Script

 

編輯 Gradle Script的方式 

開啟 Module app的 build.gradle , 在dependencies 添加兩行

dependencies {    ...    compile 'com.jakewharton:butterknife:8.4.0'    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'   ...}

省略符號代表其他已有的 dependencies 。 添加之後 sync 

啟動ButterKnife

開發環境配好後, 編碼開始

在 Activity中使用, 首先要啟動butterknife , 在 onCreate裡 setContentView 之後立即 ButterKnife.bind(this);

   protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.bind(this);    }

 

綁定View

是用@BindView 替代findViewById

public class MainActivity extends AppCompatActivity {    @BindView(R.id.btnGet)    Button mBtnGet;    @BindView(R.id.tvResult)    TextView mTvResult;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.bind(this);        mBtnGet.setText("do get");    }}

注意: 註解只能用在類成員上, 成員不能用 private 或 static 修飾, 不能用在方法中的局部變數上

綁定 資源

    @BindString(R.string.app_name)    String appName;    @BindColor(R.color.colorPrimary)    int colorPrimary;    @BindBool(R.bool.bool_name)    boolean boolName;

還支援更多類型,就不一一列舉類

 

綁定 click 事件

不用聲明 view 也不用setOnClickListener   , 參數是可有可無的, 如果不使用,不寫省事

    @OnClick(R.id.btnPost) void doPost() {        mTvResult.setText("do post done");    }

 當然也可以像 onClickListener 一樣帶上參數

    @OnClick(R.id.btnPost) void doPost(View view) {        Button btnPost = (Button)view;        mTvResult.setText("do post done " + btnPost.getText().toString());    }

還可以把強轉都省了,直接在參數上使用要轉的確切類型butterknife能幫你自動轉型

    @OnClick(R.id.btnPost) void doPost(Button btnPost) {        mTvResult.setText("do post done " + btnPost.getText().toString());    }

 

 

發

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.