1. 程式人生 > >android註解框架ButterKnife學習

android註解框架ButterKnife學習

最近學習了一個註解框架ButterKnife。地址:http://jakewharton.github.io/butterknife/https://github.com/JakeWharton/butterknife/

不同於其他的註解框架通過反射在程式碼執行階段實現對View的賦值和設定監聽事件,
ButterKnife是在程式碼編譯階段直接生成可執行的程式碼。這樣就可以避免反射帶來的執行緩慢的問題。

一,在AndroidStudio上面使用方法:

1,在專案的build.gradle中新增:

buildscript {
	
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}

我的專案的新增結果:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
2,在app模組的build.gradle中新增:

apply plugin: 'android-apt'

android {
  ...
}

dependencies {
  compile 'com.jakewharton:butterknife:8.2.1'
  apt 'com.jakewharton:butterknife-compiler:8.2.1'
}
我的專案的新增結果:

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    
    defaultConfig {
        applicationId "com.tongyan.butterknifedemo"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.jakewharton:butterknife:8.2.1'
    apt 'com.jakewharton:butterknife-compiler:8.2.1'

}

二,支援的功能;
1,在Activity中繫結view。

public class ButterKnifeDemoAct extends AppCompatActivity {
	@BindView(R.id.tv1) TextView tv1;
    @BindView(R.id.btn1) Button btn1;
    @BindView(R.id.iv1) ImageView iv1;
	 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.butter_knife_act);
		ButterKnife.bind(this);//必須在setContentView之後
       // TODO Use fields...
    }
}

2,支援資源變數的繫結:

public class ButterKnifeDemoAct extends AppCompatActivity {
	@BindView(R.id.tv1) TextView tv1;
    @BindView(R.id.btn1) Button btn1;
    @BindView(R.id.iv1) ImageView iv1;
	@BindDrawable(R.mipmap.dji_fly) Drawable flyDrawable;//圖片
    @BindDimen(R.dimen.text_size) int textSize;//Dimen
    @BindColor(R.color.red) int red;//顏色
    @BindString(R.string.text_name) String name;//字串
  
    @BindArray(R.array.flight_rc_pole_modes) String[] items;//字串陣列
	 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.butter_knife_act);
		ButterKnife.bind(this);//必須在setContentView之後
       // TODO Use fields...
    }
}	
3,支援對一個集合的View進行繫結,同時也支援對一個集合的View進行一組相同的操作。
這個操作可以是自定義的也可以是View的屬性

public class ButterKnifeDemoAct extends AppCompatActivity {

	@BindViews({R.id.editText, R.id.editText2, R.id.editText3}) List<EditText> editTexts;
	
	@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.butter_knife_act);
		ButterKnife.bind(this);//必須在setContentView之後
       // TODO Use fields...
    }
	 @OnClick(R.id.btn1)
    public void onClick() {
        Log.i(TAG, "onClick: ");
        ButterKnife.apply(editTexts, DISENABLE);//對editTexts的所有的View設定disable

    }

    @OnClick(R.id.iv1)
    public void setEnableView() {
        ButterKnife.apply(editTexts, ENABLE, true);//對editTexts的所有的View設定ensable
        ButterKnife.apply(editTexts, View.ALPHA, 0.0f);//對editTexts的所有的View設定透明
    }
	
    static final ButterKnife.Action<View> DISENABLE = new ButterKnife.Action<View>() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setEnabled(false);
        }
    };

    static final ButterKnife.Setter<View, Boolean> ENABLE = new ButterKnife.Setter<View, Boolean>() {
        @Override
        public void set(@NonNull View view, Boolean value, int index) {
            view.setEnabled(value);
        }
    };
}	
4,支援對View設定監聽方法,這個方法的引數是可選的:

既可以:

@OnClick(R.id.btn1)
    public void onClick() {
        Log.i(TAG, "onClick: ");
       // TODO Use fields...
    }
也可以:

@OnClick(R.id.btn1)
    public void onClick(View v) {
        Log.i(TAG, "onClick: ");
       // TODO Use fields...
    }
同時也支援對多個View設定同一個監聽:

@OnClick({R.id.editText, R.id.editText2, R.id.editText3})
    public void onClickEdit(View v) {
        Log.i(TAG, "onClick: ");
       // TODO Use fields...
    }
在自定義View中:

public class FancyButton extends Button {
  @OnClick
  public void onClick() {
    // TODO do something!
  }
}
對有多個回撥方法的監聽,可以只寫其中的一個方法,注意要用方法的引數進行區別執行的是什麼方法;

@OnItemSelected(R.id.spinner)
    public void onSelected(int position) {
        Log.i(TAG, "onSelected: ");
    }

    @OnItemSelected(value = R.id.spinner, callback = OnItemSelected.Callback.NOTHING_SELECTED)
    public void onNothingSelected() {
        Log.i(TAG, "onNothingSelected: ");
    }
當有一個View的id不確定是否在這個Target中可以用@Nullable @Optional註解:

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;

@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
  // TODO ...
}
總的程式碼;

public class ButterKnifeDemoAct extends AppCompatActivity {

    public static final String TAG = ButterKnifeDemoAct.class.getName();
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.btn1)
    TextView btn1;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindDrawable(R.mipmap.dji_fly)
    Drawable flyDrawable;
    @BindDimen(R.dimen.text_size)
    int textSize;
    @BindColor(R.color.red)
    int red;
    @BindString(R.string.text_name)
    String name;
    @BindViews({R.id.editText, R.id.editText2, R.id.editText3})
    List<EditText> editTexts;
    @BindArray(R.array.flight_rc_pole_modes)
    String[] items;
    @BindView(R.id.spinner)
    Spinner spinner;
    private Unbinder unbinder;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            ButterKnife.setDebug(true);
            setContentView(R.layout.butter_knife_act);
            unbinder = ButterKnife.bind(this);
            tv1.setTextSize(textSize);
            tv1.setTextColor(red);
            tv1.setText("this is ok !" + name);
            btn1.setText("you can click me !");
            iv1.setImageDrawable(flyDrawable);
            BaseAdapter leftAdapter = new MyAdapter(items,this);
            spinner.setAdapter(leftAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.btn1)
    public void onClick() {
        Log.i(TAG, "onClick: ");
        ButterKnife.apply(editTexts, DISENABLE);

    }

    @OnClick(R.id.iv1)
    public void setEnableView() {
        ButterKnife.apply(editTexts, ENABLE, true);
        ButterKnife.apply(editTexts, View.ALPHA, 0.0f);
    }

    static final ButterKnife.Action<View> DISENABLE = new ButterKnife.Action<View>() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setEnabled(false);
        }
    };

    static final ButterKnife.Setter<View, Boolean> ENABLE = new ButterKnife.Setter<View, Boolean>() {
        @Override
        public void set(@NonNull View view, Boolean value, int index) {
            view.setEnabled(value);
        }
    };

    @OnItemSelected(R.id.spinner)
    public void onSelected(int position) {
        Log.i(TAG, "onSelected: ");
    }

    @OnItemSelected(value = R.id.spinner, callback = OnItemSelected.Callback.NOTHING_SELECTED)
    public void onNothingSelected() {
        Log.i(TAG, "onNothingSelected: ");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
5,ButterKnife不只是可以在Activity中使用,還可以在其他地方,比如Dialog,Fragment,Adapter的holder中使用

/**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        @BindView(R.id.section_label)
        TextView textView;
        @Nullable @BindView(R.id.item_tv)
        TextView tv;
        Unbinder unbinder;
       

        public PlaceholderFragment() {
        }
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            unbinder = ButterKnife.bind(this, rootView);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            unbinder.unbind();
        }
    }
public class MyAdapter extends BaseAdapter {
    public static final String TAG = MyAdapter.class.getName();
    private String[] items;
    private Context context;
    private List<Unbinder> unbinders = new ArrayList<>();
    public MyAdapter(String[] items, Context context) {
        this.items = items;
        this.context = context;
    }

    @Override
    public int getCount() {
        return items.length;
    }

    @Override
    public Object getItem(int position) {
        return items[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MyHolder myHandler;
        if (convertView != null) {
            myHandler = (MyHolder) convertView.getTag();
        } else {
            convertView = LayoutInflater.from(context).inflate(R.layout.flight_rc_pole_mode_item, parent, false);
            myHandler = new MyHolder(convertView);
            convertView.setTag(myHandler);

        }
        myHandler.itemTv.setText(getItem(position).toString());
        return convertView;
    }


     class MyHolder {
        @BindView(R.id.item_tv)
        TextView itemTv;
        @OnClick(R.id.item_tv)
        public void onClick(){
            Log.i(TAG, "onClick: ");
        }
        MyHolder(View view) {
            Unbinder un = ButterKnife.bind(this, view);
            unbinders.add(un);
        }
    }

    /**
     * 只在Adapter物件銷燬的時候呼叫
     * 清除所有的繫結的MyHolder和View
     */
    public void unBinder(){
        for (Unbinder un:unbinders) {
            un.unbind();
        }
        unbinders.clear();
    }
}

6,在有生命週期的元件的銷燬方法中或一個物件銷燬的時候要un.unbind();解綁,防止記憶體洩露

生成的程式碼位置;