Android ButterKnife 使用方法總結(jié)

文/哈哩波特大

ButterKnife Introduction(介紹)


ButterKnife 是一個專注于Android系統(tǒng)的View注入框架,可視化一鍵生成。

英:

  1. Eliminate findViewById calls by using @BindView on fields.
  2. Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
  3. Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
  4. Eliminate resource lookups by using resource annotations on fields.

譯:

  1. 使用@BindView 來代替findViewById 完成View的引用。
  2. 將多個View組合成list或者array,使用actions,setters或者屬性來同時操作它們。
  3. 使用@OnClick等注解字段來注解方法,從而來代替監(jiān)聽器中的匿名內(nèi)部類。
  4. 使用@BindString等注解字段來注解字段,從而來代替Context.getString等獲取資源的方式。

How to build (如何夠賤):


Project build.gradle 添加:

dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
}

分支 module build.gradle 添加:(如果只有主項(xiàng)目可忽略)

apply plugin: 'com.jakewharton.butterknife'

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

分支 lib_common build.gradle 添加:

apply plugin: 'com.jakewharton.butterknife'

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

How to use it (如何使用):


activity使用:

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends AppCompatActivity {

    // Unbinder
    private Unbinder unbind;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setView
        setContentView(R.layout.main);
        // ButterKnife
        unbind = ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind.unbind();
    }
}

Fragment使用:

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {

    protected View rootView;
    private Unbinder unbind;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(this.getLayoutResource(), container, false);
        }
        unbind = ButterKnife.bind(this, rootView);

        return rootView;
    }

    //獲取布局文件
    protected abstract int getLayoutResource();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbind.unbind();
    }

}

Adaper使用:

import butterknife.ButterKnife;

public class MyAdapter extends BaseAdapter {

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view != null) {
            holder = (ViewHolder) view.getTag();
        } else {
            view = inflater.inflate(R.layout.item, parent, false);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }

        holder.name.setText("hello");
        return view;
    }

    static class ViewHolder {
        @BindView(R.id.name)
        TextView name;

        public ViewHolder(View view) {
            ButterKnife.bind(view);
        }
    }
}

Butterknife常用的注解:

Butterknife支持Activity,F(xiàn)ragment,View,Dialog,ViewHolder類內(nèi)部的View綁定

// 綁定View,避免findViewById,也可以用在ViewHolder里,必須是public
@BindView(R2.id.textview)  
TextView mTextView; 

// 綁定多個view,只能用List不能用ArrayList
@BindViews({ R2.id.button1, R2.id.button2,  R2.id.button3})  
List<Button> buttonList; 

// 綁定點(diǎn)擊事件
@OnClick(R2.id.submit)
public void submit(View view) {...}

// 多個id綁定點(diǎn)擊事件(8.4.0不支持此寫法)
// 在 view.getId()方法中,系統(tǒng)返回的值是R類中的id而不是R2中的id,而且兩個R類中相同變量的id并不相同,所以會翻車。
@OnClick({R.id.example_btn1, R.id.example_btn2, R.id.example_btn3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.example_btn1:
                break;
            case R.id.example_btn2:
                break;
            case R.id.example_btn3:
                break;
        }
     }

//(8.4.0需要單個綁定)
@OnClick(R2.id.txt_bind_we_chat_btn)
public void onBindWeChatClick(View v) {
    bindWeChat();
}

@OnClick(R2.id.txt_bind_phone_btn)
  public void onBIndPhoneClick(View v) {
    bindPhoe();
}

@OnClick(R2.id.back)
public void onBackClick() {
    finish();
}

// 綁定長按事件 
@OnLongClick( R2.id.button1 )  
public boolean showToast(){   
    return true ;  
}

// itemSelected監(jiān)聽
@OnItemSelected(R2.id.list_view)
void onItemSelected(int position) {...}

// itemClick監(jiān)聽
@OnItemClick(R2.id.list_view) 
void onItemClick(int position) {...}

// 焦點(diǎn)改變監(jiān)聽
@OnFocusChange(R2.id.list_view) 
void onFocusChanged(boolean focused){...}

// itemLongClick長按監(jiān)聽
@OnItemLongClick(R2.id.list_view) 
boolean onItemLongClick(int position){...}

// viewpager切換監(jiān)聽
@OnPageChange(R2.id.example_pager) 
void onPageSelected(int position){...}

// et內(nèi)容改變監(jiān)聽
@OnTextChanged(R2.id.example_et) 
void onTextChanged(CharSequence text)

// 綁定string.xml里的字符串
@BindString(R2.string.example_name)   
String exampleName;

// 綁定string里面array數(shù)組 
@BindArray(R2.array.city)  
String [] citys;  

// 綁定色值在color文件中 
@BindColor( R2.color.black) 
int black;

// 綁定圖片資源
@BindBitmap( R.mipmap.wifi) 
Bitmap bitmap;

// 綁定dimens
@BindDimen(R.dimen.example_width) 
int exampleWidth;

// 綁定圖片
@BindDrawable(R.drawable.example_pic)
Drawable examplePic;

// 綁定Integer類型的resource ID
@BindInt

// 綁定boolean值
@BindBool

ButterKnife Zelezny插件(自動生成代碼)


How to install (如何安裝)

  • in Android Studio:FileSettingsPluginsBrowse repositories→搜索Android ButterKnife ZeleznyInstallRestart Android Studio(安裝后重啟生效)

  • download ButterKnife:FileSettingsPluginsInstall plugin from disk(安裝后重啟生效)

How to use it (如何使用):

zelezny_animated.gif

  1. Make sure you have latest Butterknife lib on your classpath
  2. Right click on usage of desired layout reference (e.g. R.layout.main in your Activity or Fragment), then Generate and Generate ButterKnife Injections
  3. Pick injections you want, you also have an option to create ViewHolder for adapters.
  4. Click Confirm and enjoy injections in your code with no work!

ButterKnife 代碼混淆:


-keep class butterknife.** { *; }  
-dontwarn butterknife.internal.**  
-keep class **$$ViewBinder { *; }  
  
-keepclasseswithmembernames class * {  
    @butterknife.* <fields>;  
}  
  
-keepclasseswithmembernames class * {  
    @butterknife.* <methods>;  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容