欢迎使用CSDN-markdown编辑器

来源:互联网 发布:剑网三最帅花哥数据 编辑:程序博客网 时间:2024/04/29 06:31

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

原创粉丝点击