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

Android Studio中ButterKnife插件的安装与使用

2016-07-07 15:22 579 查看
最近用到Android Butterknife Zelezny插件,感觉特别棒!在Android开发过程中,我们会写大量的初始化控件和设置控件点击事件的操作,这样简单而重复的工作让人觉得麻烦而且没意思,可以采用注解的方式去实现,而ButterKnife是注解中相对简单易懂的开源框架。

一、Android Studio中安装ButterKnife插件:

(1)和安装其他插件一样,首先,打开:settings->plugins界面









(2)重新启动了Android Studio之后,此时我们已经安装了ButterKnife插件了,接下来在项目的bulid.gradle中添加依赖,如下图所示:

compile 'com.jakewharton:butterknife:7.0.0'




(3)重新编译一下该项目,就可以在代码中使用注解的方式了,在这里我们先写一个简单的布局文件来举例:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

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

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

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

<ImageView
android:id="@+id/iv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />

</LinearLayout>


如果不使用ButterKnife插件,我们需要在 重写的onCreate()方法中通过findViewById()对控件进行实例化并对控件添加事件监听,如下如所示:



代码还是比较简洁,这也是因为我们的布局相对而言比较简单,可是如果布局比较复杂的话,这样的操作就显得比较繁琐。现在我们只需要简单点击几下鼠标就可以完成这些操作了。

(4)鼠标双击选择布局文件名,右键(或者直接快捷键:Alt+Insert)





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: