Android Studio ButterKnife 插件安装使用

   利用ButterKnife之后就不需要在代码中写大量的findviewbyId了,通过ButterKnife自动生成的方式,就可以用注解代替以前的findviewbyId,具体如下

1、打开Studio 安装Plugins的界面,选择Preferences



在Browse repositories里选择需要安装的插件,安装完成之后可能需要重启studio

2、配置方法

在app里的bulid.gradle中添加依赖,代码如下

//加在app的build.gradle 里apply plugin: 'com.android.application'下面
apply plugin: 'android-apt'

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

}
在Project的bulid.gradle中添加依赖,代码如下

buildscript {
    ...
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

3、使用注解代替以前的findviewById

3.1 实例的布局文件

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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="okhttp.jason.com.okhttpdemo.MainActivity">

    <Button
        android:id="@+id/bt_demo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"/>
</LinearLayout>

3.2 在代码中使用注解

 在上述布局文件所引用的java类中,在setContentView之后添加  ButterKnife.bind(this),然后选择上述布局文件名,右键选择Generate。



选择需要用到的控件,确认之后就会自动生成各个在布局文件中带有id 属性的view的注解形式,如下

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.bt_demo)
    Button btDemo;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;

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

使用ButterKnife注解绑定控件后报NullPointException,注意查看是否按照步骤2里配置了ButterKnife

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值