Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android注解框架ButterKnife學習

android注解框架ButterKnife學習

編輯:關於Android編程

不同於其他的注解框架通過反射在代碼運行階段實現對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 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 DISENABLE = new ButterKnife.Action() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setEnabled(false);
        }
    };

    static final ButterKnife.Setter ENABLE = new ButterKnife.Setter() {
        @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 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 DISENABLE = new ButterKnife.Action() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setEnabled(false);
        }
    };

    static final ButterKnife.Setter ENABLE = new ButterKnife.Setter() {
        @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 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();解綁,防止內存洩露

生成的代碼位置;

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved