ButterKnife
butterknife github的官網:
https://github.com/JakeWharton/butterknife
官方介紹butterknife:
Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.
- Eliminate findViewById calls by using @BindView on fields.
- Group multiple views in a list or array. Operate on all of them at
once with actions, setters, or properties. - Eliminate anonymous inner-classes for listeners by annotating
methods with @OnClick and others. - Eliminate resource lookups by using resource annotations on
fields.
也就是說butterknife使用註解的方式來綁定安卓顯示控件。
第一個butterknife Demo
(1)在Project的 build.gradle 中添加如下依賴代碼:
buildscript {
repositories {
mavenCentral()
google()
}
dependencies {
//classpath 'com.jakewharton:butterknife-gradle-plugin:10.1.0'
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1' //添加這一行
}
}
(2)在app\build.gradle 中添加庫依賴
dependencies {
compile 'com.jakewharton:butterknife:8.8.1' //添加這二行
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' //添加這二行
}
細心的人可以會發現,爲什麼我沒有使用最新的10.1.0版本,好吧,我承認添加最新的版本把錯,而我沒有搞定,就使用一個早期的版本來使用了.
(3) 使用butterknife
在strings.xml中添加一個字符串
<resources>
<string name="login_error">login error</string>
</resources>
佈局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="input user name"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="input password"
app:layout_constraintTop_toBottomOf="@id/user_name"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="@+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
app:layout_constraintTop_toBottomOf="@id/password"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
具體實現了:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@BindView(R.id.user_name) EditText username;
@BindView(R.id.password) EditText password;
@BindString(R.string.login_error) String loginErrorMessage;
@OnClick(R.id.submit) void submit() {
// TODO call server...
Log.i(TAG,"submit---username:"+username.getText().toString());
Log.i(TAG,"submit---password:"+password.getText().toString());
Log.i(TAG,"submit---loginErrorMessage:"+loginErrorMessage);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this); //綁定ButterKnife
}
}
界面效果:
當我們輸入user name爲test,密碼爲1234時,打印的日誌爲:
com.readygo.butterknifedemo03 I/MainActivity: submit---username:test submit---password:1234
com.readygo.butterknifedemo03 I/MainActivity: submit---loginErrorMessage:login error
在這個Demo中,我們使用了butterknife綁定控件,字符串 , 做完這個Demo後,其實butterknife的使用,也就入門了.
ButterKnife詳細介紹
我們參考:
Android Butterknife使用方法總結
https://www.jianshu.com/p/3678aafdabc7
更全面的瞭解ButterKnife的使用.
ButterKnife的註冊與綁定
ButterKnife使用心得與注意事項:
1、在Activity 類中綁定 :ButterKnife.bind(this);必須在setContentView();之後綁定;且父類bind綁定後,子類不需要再bind。
2、在非Activity 類(eg:Fragment、ViewHold)中綁定: ButterKnife.bind(this,view);這裏的this不能替換成getActivity()。
3、在Activity中不需要做解綁操作,在Fragment 中必須在onDestroyView()中做解綁操作。
4、使用ButterKnife修飾的方法和控件,不能用private or static 修飾,否則會報錯。錯誤: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)
5、setContentView()不能通過註解實現。(其他的有些註解框架可以)
6、使用Activity爲根視圖綁定任意對象時,如果你使用類似MVC的設計模式你可以在Activity 調用ButterKnife.bind(this, activity),來綁定Controller。
7、使用ButterKnife.bind(this,view)綁定一個view的子節點字段。如果你在子View的佈局裏或者自定義view的構造方法裏 使用了inflate,你可以立刻調用此方法。或者,從XML inflate來的自定義view類型可以在onFinishInflate回調方法中使用它。
在Activity中綁定ButterKnife
綁定Activity 必須在setContentView之後。使用ButterKnife.bind(this)進行綁定。代碼如下:
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定初始化ButterKnife
ButterKnife.bind(this);
}
}
在Fragment中綁定ButterKnife
Fragment的生命週期不同於activity。在onCreateView中綁定一個Fragment時,在onDestroyView中將視圖設置爲null。當你調用bind來爲你綁定一個Fragment時,Butter Knife會返回一個Unbinder的實例。在適當的生命週期(onDestroyView)回調中調用它的unbind方法進行Fragment解綁。使用ButterKnife.bind(this, view)進行綁定。代碼如下:
public class ButterknifeFragment extends Fragment{
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
//返回一個Unbinder值(進行解綁),注意這裏的this不能使用getActivity()
unbinder = ButterKnife.bind(this, view);
return view;
}
/**
* onDestroyView中進行解綁操作
*/
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
在Adapter中綁定ButterKnife
在Adapter的ViewHolder中使用,將ViewHolder加一個構造方法,在new ViewHolder的時候把view傳遞進去。使用ButterKnife.bind(this, view)進行綁定,代碼如下:
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.testlayout, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
holder.name.setText("Donkor");
holder.job.setText("Android");
// etc...
return view;
}
static class ViewHolder {
@BindView(R.id.title) TextView name;
@BindView(R.id.job) TextView job;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
ButterKnife的基本使用
綁定View
控件id 註解: @BindView()
@BindView( R2.id.button)
public Button button;
佈局內多個控件id 註解: @BindViews()
public class MainActivity extends AppCompatActivity {
@BindViews({ R2.id.button1, R2.id.button2, R2.id.button3})
public List<Button> buttonList ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
buttonList.get( 0 ).setText( "hello 1 ");
buttonList.get( 1 ).setText( "hello 2 ");
buttonList.get( 2 ).setText( "hello 3 ");
}
}
綁定資源
綁定string 字符串:@BindString()
public class MainActivity extends AppCompatActivity {
@BindView(R2.id.button) //綁定button 控件
public Button button ;
@BindString(R2.string.app_name) //綁定資源文件中string字符串
String str;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
button.setText( str );
}
}
綁定string裏面array數組:@BindArray()
<resources>
<string name="app_name">城市</string>
<string-array name="city">
<item>北京市</item>
<item>天津市</item>
<item>哈爾濱市</item>
<item>大連市</item>
<item>香港市</item>
</string-array>
</resources>
------------------------------------------------------------------------------
public class MainActivity extends AppCompatActivity {
@BindView(R2.id.button) //綁定button 控件
public Button button ;
@BindString(R2.string.app_name) //綁定資源文件中string字符串
String str;
@BindArray(R2.array.city) //綁定string裏面array數組
String [] citys ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
button.setText(citys[0]);
}
}
綁定Bitmap 資源:@BindBitmap( )
public class MainActivity extends AppCompatActivity {
@BindView( R2.id.imageView ) //綁定ImageView 控件
public ImageView imageView ;
@BindBitmap( R2.mipmap.bm)//綁定Bitmap 資源
public Bitmap bitmap ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
imageView.setImageBitmap(bitmap);
}
}
綁定一個顏色值:@BindColor( )
public class MainActivity extends AppCompatActivity {
@BindView( R2.id.button) //綁定一個控件
public Button button;
@BindColor( R2.color.colorAccent ) //具體色值在color文件中
int black ; //綁定一個顏色值
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
button.setTextColor( black );
}
}
事件綁定
綁定點擊事件:
綁定控件點擊事件:@OnClick( )
綁定控件長按事件:@OnLongClick( )
public class MainActivity extends AppCompatActivity {
@OnClick(R2.id.button1 ) //給 button1 設置一個點擊事件
public void showToast(){
Toast.makeText(this, "is a click", Toast.LENGTH_SHORT).show();
}
@OnLongClick( R2.id.button1 ) //給 button1 設置一個長按事件
public boolean showToast2(){
Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();
return true ;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
}
}
指定多個id綁定事件:
public class MainActivity extends AppCompatActivity {
//Tip:當涉及綁定多個id事件時,我們可以使用Android studio的Butterknife
//插件zelezny快速自動生成的,之後在下面會有介紹安裝插件與使用
@OnClick({R.id.ll_product_name, R.id.ll_product_lilv, R.id.ll_product_qixian, R.id.ll_product_repayment_methods})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.ll_product_name:
System.out.print("我是點擊事件1");
break;
case R.id.ll_product_lilv:
System.out.print("我是點擊事件2");
break;
case R.id.ll_product_qixian:
System.out.print("我是點擊事件3");
break;
case R.id.ll_product_repayment_methods:
System.out.print("我是點擊事件4");
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
}
}
通過上面的例子可以看出多條點擊事件是沒有用R2的方式,如果一定要使用R2的寫法,可以單一逐次寫,正確的寫法如下:
public class MainActivity extends AppCompatActivity {
@OnClick(R2.id.ll_product_name)
public void onViewClicked1(View view) {
System.out.print("我是點擊事件1");
}
@OnClick(R2.id.ll_product_lilv)
public void onViewClicked2(View view) {
System.out.print("我是點擊事件2");
}
@OnClick(R2.id.ll_product_qixian)
public void onViewClicked3(View view) {
System.out.print("我是點擊事件3");
}
@OnClick(R2.id.ll_product_repayment_methods)
public void onViewClicked4(View view) {
System.out.print("我是點擊事件4");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
}
}
自定義View使用綁定事件
不用指定id,直接註解OnClick。看代碼覺得好像跟實現點擊事件的方法類似。實際上並沒有實現OnClickListener接口。代碼如下:
public class MyButton extends Button {
@OnClick
public void onClick() {}
}
綁定監聽:
Listeners可以自動配置到方法中
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
自定義一個特定類型,它將自動被轉換
@OnClick(R.id.submit)
public void sayHi(Button button) {//看括號內參數的變化就明白了
button.setText("Hello!");
}
在單個綁定中指定多個id,用於公共事件處理。這裏舉例點擊事件。其他的事件監聽同樣也是可以的。
@OnClick(R.id.submitCode,R.id.submitFile,R.id.submitTest)
public void sayHi(Button button) {//多個控件對應公共事件
button.setText("Success!");
}
自定義視圖可以通過不指定ID來綁定到它們自己的監聽器。
public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
Listener中多方法註解
方法註解,其對應的監聽器有多個回調,可用於綁定到其中任何一個。每個註解都有一個它綁定的默認回調。使用回調參數指定一個替換。以Spinner爲例。
原本代碼:
Spinner s=new Spinner(this);
//原始方法:Spinner 條目選擇監聽事件 正常寫法
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
通過 Butter Knife 註解方式
public class MainActivity extends AppCompatActivity {
/*利用註解對Spinner item 作選擇監聽事件處理方式*/
@OnItemSelected(R.id.my_spiner)//默認callback爲ITEM_SELECTED
void onItemSelected(int position) {
Toast.makeText(this, "position: " + position, Toast.LENGTH_SHORT).show();
}
/*
* 註解onNothingSelected,需要在註解參數添加一個callback,
* 注意的是Spinner中只要有數據,默認都會選中第0個數據,所以想進入到onNothingSelected()方法,就需要把Adapter中的數據都清空
*/
@OnItemSelected(value = R.id.my_spiner, callback = OnItemSelected.Callback.NOTHING_SELECTED)
void onNothingSelected() {
Toast.makeText(this, "Nothing", Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind( this ) ;
Spinner s=new Spinner(this);
}
}
@OnCheckedChanged監聽的使用
原方法應是:setOnCheckedChangeListener()。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="@+id/rg_main"
android:layout_width="fill_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:background="@color/white"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rg_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:text="@string/nav_one" />
<RadioButton
android:id="@+id/rg_wealth"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:text="@string/nav_two" />
<RadioButton
android:id="@+id/rg_account"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:text="@string/nav_four" />
</RadioGroup>
</LinearLayout>
-------------------------------------------------------------------------
@OnCheckedChanged({R.id.rg_home,R.id.rg_wealth,R.id.rg_account})
public void OnCheckedChangeListener(CompoundButton view, boolean ischanged ){
switch (view.getId()) {
case R.id.rg_home:
if (ischanged){//注意:這裏一定要有這個判斷,只有對應該id的按鈕被點擊了,ischanged狀態發生改變,纔會執行下面的內容
//這裏寫你的按鈕變化狀態的UI及相關邏輯
}
break;
case R.id.rg_wealth:
if (ischanged) {
//這裏寫你的按鈕變化狀態的UI及相關邏輯
}
break;
case R.id.rg_account:
if (ischanged) {
//這裏寫你的按鈕變化狀態的UI及相關邏輯
}
break;
default:
break;
}
}
使用findById:
Butter Knife仍然包含了findById()方法,用於仍需從一個view ,Activity,或者Dialog上初始化view的時候,並且它可以自動轉換類型。
View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);
TextView lastName = ButterKnife.findById(view, R.id.last_name);
ImageView iv = ButterKnife.findById(view, R.id.iv);
設置多個view的屬性
apply()
作用:允許您立即對列表中的所有視圖進行操作。
Action和Setter接口
作用:Action和Setter接口允許指定簡單的行爲。
public class MainActivity extends AppCompatActivity {
@BindViews({R2.id.first_name, R2.id.middle_name, R2.id.last_name})
List<EditText> nameViews;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//綁定activity
ButterKnife.bind(this);
//設置多個view的屬性
//方式1:傳遞值
ButterKnife.apply(nameViews, DISABLE);
//方式2:指定值
ButterKnife.apply(nameViews, ENABLED, false);
////方式3 設置View的Property
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);//一個Android屬性也可以用於應用的方法。
}
/*
* Action接口設置屬性
*/
static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
@Override
public void apply(View view, int index) {
view.setEnabled(false);//目的是使多個view都具備此屬性
}
};
/*
* Setter接口設置屬性
*/
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(View view, Boolean value, int index) {
view.setEnabled(value);//目的是使多個view都具備此屬性,可變boolean值是可以傳遞的
}
};
}
更多綁定註解:
@BindView—->綁定一個view;id爲一個view 變量
@BindViews —-> 綁定多個view;id爲一個view的list變量
@BindArray—-> 綁定string裏面array數組;@BindArray(R.array.city ) String[] citys ;
@BindBitmap—->綁定圖片資源爲Bitmap;@BindBitmap( R.mipmap.wifi ) Bitmap bitmap;
@BindBool —->綁定boolean值
@BindColor —->綁定color;@BindColor(R.color.colorAccent) int black;
@BindDimen —->綁定Dimen;@BindDimen(R.dimen.borth_width) int mBorderWidth;
@BindDrawable —-> 綁定Drawable;@BindDrawable(R.drawable.test_pic) Drawable mTestPic;
@BindFloat —->綁定float
@BindInt —->綁定int
@BindString —->綁定一個String id爲一個String變量;@BindString( R.string.app_name ) String meg;
更多事件註解:
@OnClick—->點擊事件
@OnCheckedChanged —->選中,取消選中
@OnEditorAction —->軟鍵盤的功能鍵
@OnFocusChange —->焦點改變
@OnItemClick item—->被點擊(注意這裏有坑,如果item裏面有Button等這些有點擊的控件事件的,需要設置這些控件屬性focusable爲false)
@OnItemLongClick item—->長按(返回真可以攔截onItemClick)
@OnItemSelected —->item被選擇事件
@OnLongClick —->長按事件
@OnPageChange —->頁面改變事件
@OnTextChanged —->EditText裏面的文本變化事件
@OnTouch —->觸摸事件
@Optional —->選擇性注入,如果當前對象不存在,就會拋出一個異常,爲了壓制這個異常,可以在變量或者方法上加入一下註解,讓注入變成選擇性的,如果目標View存在,則注入, 不存在,則什麼事情都不做
Butterknife插件:zelezny
插件安裝:
工具欄File 找到Settings…或者使用快捷點Ctrl+Alt+s 打開。在Plugins搜索zelezny下載插件並安裝,重啓Android Studio
插件使用:
安裝完成插件後,會提示重啓AS,重啓完後,使用的話, 需要將光標移到setContentView(R.layout.acty_login),將光標放到R.layout.acty_login,然後右鍵Generate–ButterKnife Injections(by ParfoisMeng)。對於多個需要綁定的id,省下了需要自己手動敲打代碼的時間。
參考資料
Android開發之手把手教你寫ButterKnife框架(一)
https://blog.csdn.net/johnny901114/article/details/52662376