Android-butterknife 簡單使用

jopen 9年前發布 | 1K 次閱讀 Java Android

butterknife是一個依賴注入框架,可以省去我們findviewbyid()操作,以前一直使用xutils中的注入功能,這次體驗了一下這個,感覺還是有一些差別的。

使用說明:

@viewinject(r.id.xxx)

Textview  xxx;

這里的textview不能是private活著static,否則報錯,在xutils中沒有這個限制


@onLongClick(R.id.xxx)

boolean method()

這里的method同樣不能是private,而且返回類型必須是boolean類型的。



具體測試代碼:

1.添加依賴:

compile 'com.jakewharton:butterknife:6.1.0'

2.布局代碼:

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

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

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

</RelativeLayout></pre>
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);  

// bt_changetext.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
// }
// });
}

// @OnClick(R.id.bt_changetext)
// void changeText() {
// tv_hello.setText("hello my dear graypn!");
// }

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

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!