Andoid项目添加ButterKnife注解框架

项目地址

https://github.com/JakeWharton/butterknife

添加依赖

project 中build.gradle添加

buildscript {
    repositories {
        mavenCentral()  
    }
    dependencies {
        classpath'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}

module中build.gradle添加

applyplugin:'com.neenbedankt.android-apt'

dependencies {
    compile'com.jakewharton:butterknife:8.0.1'
    apt'com.jakewharton:butterknife-compiler:8.0.1'
}

使用方法

http://jakewharton.github.io/butterknife/

Activity中

class ExampleActivity extends Activity {
    @BindView(R.id.title) TextView title;
    @BindView(R.id.subtitle) TextView subtitle; 
    @BindView(R.id.footer) TextView footer; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.simple_activity);
        ButterKnife.bind(this);
        // TODO Use fields... 
    }
}

Fragment中

public class FancyFragment extends Fragment {
    @BindView(R.id.button1) Button button1;
    @BindView(R.id.button2) Button button2;

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fancy_fragment, container, false);
        ButterKnife.bind(this, view);
        // TODO Use fields...
        return view;
    }
}

ViewHolder中

static class ViewHolder {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
        ButterKnife.bind(this, view);
    }
}

其他用法

  • VIEW LISTS
  • LISTENER BINDING
  • BINDING RESET (Fragment中用)
  • OPTIONAL BINDINGS
  • MULTI-METHOD LISTENERS
  • BONUS

Android Studio插件

Android ButterKnife Zelezny

你可能感兴趣的:(Andoid项目添加ButterKnife注解框架)