Android Studio ButterKnife 插件安装使用

来源:互联网 发布:淘宝模板怎么用 编辑:程序博客网 时间:2024/06/15 00:36

   利用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