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

Android之---ButterKnife-View注入框架(简单介绍和在Studio中安装)

2016-12-07 10:53 531 查看

ButterKnife-View注入框架(简单介绍和在Studio中安装)

1.简单介绍

Butter Knife使用简单介绍

作为一名Android开发,是不是经常厌烦了大量的findViewById以及setOnClickListener代码,而ButterKnife是一个专注于Android系统的View注入框架,让你从此从这些烦人臃肿的代码中解脱出来。先来看一段代码示例说明下ButterKnife是如何简化代码的:

注意:如果你是使用的Eclipse引用该library,你需要参考这里Eclipse Configuration做一些配置,否则会运行出错。



而用ButterKnife之后的代码是这样的:



Butter Knife特性

支持 Activity 中的 View 注入

支持 View 中的 View 注入

支持 View 事件回调函数注入

目前支持如下事件回调函数:

View: @OnLongClick and @OnFocusChanged.

TextView: @OnEditorAction.

AdapterView: @OnItemClick and @OnItemLongClick.

CompoundButton: @OnCheckedChanged.

下面来看一些注入的示例代码:

在Activity 中注入



在Fragment中注入



在ViewHolder中注入



注入回调函数

下面是几种注入回调函数的方法示例:



Reset函数

如果需要在 界面 销毁的时候,把注入的 View 设置为 Null, 则可以用 reset 函数:



另外 还支持 可选的 View 注入,如果该 View 没有,就没有吧:



还有两个 findViewById 函数来简化查找 View 的方式,如果上面都满足不了你的需求,你可以用用他们:



如果你是用Studio开发的,在Studio中安装Butter Knife插件简单介绍如下:

2.插件安装

1.本人使用的是studio2.0,在点击File—>Settings—>Plugins如下:



2.点击上图红圈处选项,在搜索框中输入Zelezny,如果没有安装右上角会提示你安装(我的是已经安装过的!),安装后会提示重启Studio,重启即可



3.Butter Knife使用

1.在bulid.gradle中添加依赖



重新编译一下该项目,通过后继续操作。

2.具体使用(对于这样的xml文件)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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=".MainActivity">

<TextView
android:id="@+id/text_veiw_tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView 1" />

<Button
android:id="@+id/button_bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />

<TextView

android:id="@+id/text_veiw_tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView 2" />

<Button
android:id="@+id/button_bt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />

</LinearLayout>


在对应的Java类中的布局处—>右键







在对应的View中形成的标注如下



参考文档:

http://stormzhang.com/openandroid/android/2014/01/12/android-butterknife/

http://blog.csdn.net/cxc19890214/article/details/47430547
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息