Android中butterknife框架的使用
####Butter Knife:用來綁定Android中view的一個框架。
####介紹文檔:http://jakewharton.github.io/butterknife/
- 1.添加gradle依賴,在app的build.gradle中添加如下代碼:
dependencies {
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}
- 2.在xml文件中隨便添加幾個控件,並且添上id
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.example.hch.butterknifedemo.MainActivity">
<TextView
android:id="@+id/butterknife_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="@+id/butterknife_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="這是一個按鈕" />
<ImageView
android:id="@+id/butterknife_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
- 使用@BindView註解來代替findviewvyid
public class MainActivity extends AppCompatActivity {
@BindView(R.id.butterknife_textview)
TextView myTextview;
@BindView(R.id.butterknife_button)
Button myButton;
@BindView(R.id.butterknife_imageview)
ImageView myImageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
myTextview.setText("butter knife框架的使用");
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"這是按鈕的點擊事件",Toast.LENGTH_SHORT).show();
}
});
myImageview.setBackgroundResource(R.drawable.a);
}
}
###這就是ButterKnife的簡單使用,是不是很方便,而且減少了很多代碼量
###ButterKnife除了能綁定id外還能綁定res文件夾下的各種資源,如:
@BindString(R.string.app_name)
String name;
@BindDrawable(R.drawable.a)
Drawable photo;
@BindColor(R.color.colorPrimary)
Color primary;
...........
####只要根據不同的資源選擇對應的註解即可
####我這邊介紹的還只是鳳毛麟角,在此給大家介紹幾篇文章,寫的都算比較詳細的:
http://www.jianshu.com/p/9ad21e548b69
http://www.360doc.com/content/16/0715/17/8279768_575749596.shtml
http://www.jianshu.com/p/0f3f4f7ca505