butterknife是一个依赖注入框架,可以省去我们findviewbyid()操作,以前一直使用xutils中的注入功能,这次体验了一下这个,感觉还是有一些差别的。
使用说明:
@viewinject(r.id.xxx)
Textview xxx;
这里的textview不能是private活着static,否则报错,在xutils中没有这个限制
@onLongClick(R.id.xxx)
boolean method()
这里的method同样不能是private,而且返回类型必须是boolean类型的。
具体测试代码:
1.添加依赖:
<span style="font-size:14px;">compile 'com.jakewharton:butterknife:6.1.0'</span>
2.布局代码:
<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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></span>
3.activity代码:
<span style="font-size:14px;">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;
}
}</span>