Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ButterKnife 依賴注入框架簡單實用指南

編輯:關於 Android 程式設計

ButterKnife 是一個依賴注入框架,可以省去繁瑣的 findViewById() 操作。過去一直使用 xUtils 的注入功能,這次實際體驗 ButterKnife 後,發現兩者之間存在一些差異。

基本用法

使用 @InjectView(R.id.xxx) 標註欄位即可省去 findViewById,但需注意被標註的 TextView 不能宣告為 private 或 static,否則會報錯(xUtils 則無此限制)。

此外,@OnLongClick(R.id.xxx) 這類事件綁定的方法同樣不能是 private,且回傳型別必須為 boolean。

測試程式碼

1. 添加依賴:

compile 'com.jakewharton:butterknife:6.1.0'

2. 版面配置:

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/bt_changetext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="改變文字" />
</RelativeLayout>

3. Activity 程式碼:

public class MainActivity extends ActionBarActivity {

    @InjectView(R.id.tv_hello)
    TextView tv_hello;

    @InjectView(R.id.bt_changetext)
    Button bt_changetext;

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

    @OnLongClick(R.id.bt_changetext)
    boolean changeTextByLongClick() {
        tv_hello.setText("hello my dear graypn!");
        return true;
    }
}

可以看到,透過 ButterKnife 的註解,原本冗長的 findViewById 與 setOnClickListener 都被大幅簡化,程式碼更為乾淨直觀。只要在 onCreate 中呼叫 ButterKnife.inject(this),即可完成所有綁定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved