ButterKnife 入门

layout: post
title: "ButterKnife 入门"
date: 2016年10月21日 20:57:25
comments: true
external-url:
categories: android

介绍

项目介绍
项目 github 地址

这里注意如果只按项目介绍的 Download 来添加依赖的话

Gradle

compile 'com.jakewharton:butterknife:8.4.0'

apt 'com.jakewharton:butterknife-compiler:8.4.0'

会出错,出错信息

Error:(29, 0) Could not find method apt() for arguments [com.jakewharton:butterknife-compiler:8.4.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

我们点开 github 地址来看使用方法.

  • 在 build.gradle 文件中加入 android-apt 插件
buildscript {
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}
  • 应用该插件和加入依赖
apply plugin: 'android-apt'

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

使用

在文件 ButterKnifeHelloWorld\app\src\main\res\layout\activity_main.xml 中的 TextView 中加入 id

再到 MainActivity 中加入

@BindView(R.id.txt_butter_knife) TextView mTxtButterKnife;

onCreate 方法中加入

ButterKnife.bind(this);
mTxtButterKnife.setText("Butter Knife Hello World!");

这样就可以运行了.

代码地址

ButterKnifeHelloWorld.png

Why

使用 ButterKnife 可以免去我们使用 findViewById 方法来定位,让代码更简洁

你可能感兴趣的:(ButterKnife 入门)