您的位置:首页 > 移动开发 > Android开发

ButterknifeZelezny在AndroidStudio中的配置与使用方法

2016-07-05 16:08 519 查看
     前言:当我们在Activity或Fragment要引用layout布局下的控件的时候,一般做法是findViewById(R.id.XXX)  当你布局文件控件较多、教复杂的时候要写几十个findViewById()这尼玛,全是重复代码,完全是体力活!这个时候是不是想:这完全不是我们程序员干的事情。这个时候使用Butterknife插件就可以很好的解决这些问题,什么事情都想着让程序自动化帮忙减轻工作量,这个开源库可以让我们从大量的findViewById()和setonclicktListener()解放出来。

     
git项目地址:https://github.com/avast/android-butterknife-zelezny

先来看看效果图,还是很酷炫的

         


   1、插件安装

        安装方式分为两种:

     1.1   找到file->Settrings->Plugins->在搜索框中搜索ButterKnife Zelezny  然后点击添加插件就可以了,如图

(我这里已经添加成了所以显示的是Uninstall Piugin)



  1.2  下载ButterKnife Zelezny的Jar包添加进去(点我下载Jar包),然后点击上图的“Install Plugin Form disk..”按钮,将刚刚下载的jar包添加进去,点击“ok”后 AndroidStuido会自动重启

 2、添加依赖库

      在build.gradle中加入如下代码

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

dependencies {
compile 'com.jakewharton:butterknife:8.0.1'
apt 'com.jakewharton:butterknife-compiler:8.0.1'
}
3、在代码中如何使用

     如下是activity_main.layout代码,代码很简单,纯粹是为了演示   

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.farmkeeperfly.MainActivity">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>     在Activity中,双击选择layout,右键选择Generate图1(或者直接Alt+Insert快捷键都行图2)选择Butterknife那项如图2:
图1:



图2:



  这个时候会弹出如图所示选择框,这个是我们就可以选择需要引入的布局控件以及他们的OnClick事件,细心的同学还会发现,左下角还有一个CreateViewHolder选项,是的它也支持Adapter中的运用,具体步骤一样。



  勾选完以上选项后点击“Confirm”按钮就完成了,看下最终图



总结: ButterknifeZelezny配置简单、实用。但是有几点需要主机

  1、layout布局控件需要有id才能被正常引用

          2、记得加上ButterKnife.bind(this)方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息