ButterKnife 8.5.1的配置与使用

本文介绍ButterKnife框架在Android开发中的应用,通过实例演示如何避免繁琐的findViewById及setOnClickListener操作,实现更简洁高效的UI绑定。

1.无意间发现一个有趣的Android系统的View注入框架,它的作用就是减少大量的findViewById以及setOnClickListener代码,实话实说每次写findViewById的时候确实很恼火,实在是太无聊!如果没有听过ButterKnife,反正我也不会说,百度一堆。

2.这是一个github上的开源项目,这是地址位置:https://github.com/JakeWharton/butterknife,我知道你是不会去看的!

3.由于现在已经是8.5.1版本了,和以前的配置就有些不同,不过也不是复杂。废话不多说,直接开始吧!

4.首先新建个android studio的项目,这么简单就不说了,然后就需要一些简单的配置,看图

这里写图片描述
(1)首先,找到Gradle下这两个文件,两个是不一样的,分了1,2
这里写图片描述
(2)在1中的依赖项中加入一行:classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
这里写图片描述
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

然后refresh一下Gradle就可以好好写代码了 ,确实挺容易,不过笔者当时习惯性的只导入了后者,毕竟一般的库都这么用的,结果,根本用不了,因此解决了之后才打算写个教程,让大家少走弯路。

5.为了测试,笔者就简单的加了个Button做了个测试,布局代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xugongming38.bufferknife.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/text"/>

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button" />
</RelativeLayout>

6.下面就是MainActivity的代码,没有findViewByID,OnClickListener什么的果然再也不用写,时候不是很优雅

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.text) TextView tv;
    @BindView(R.id.button) Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this) ;
    }

    @OnClick(R.id.button)
    void  click() {
        tv.setText("Hello ButterKnife");
    }
}

7.很简单,就是点了按钮之后把文本框hello world变成Hello ButterKnife,看看效果吧

这里写图片描述
这里写图片描述

8.果然有效果了,当然了用法远远不止这么点,看到有人写了一篇介绍很全面的文章,我就不多此一举了,附上链接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值