加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ButterKnife依赖注入框架的引入和使用

发布时间:2020-12-14 05:12:14 所属栏目:百科 来源:网络整理
导读:俗话说:“不会偷懒的程序员不是好的程序员

俗话说:“不会偷懒的程序员不是好的程序员!”。作为一名Android开发,是不是经常厌烦了大量的findViewById以及setOnClickListener代码,而ButterKnife是一个专注于Android系统的View注入框架,让你从此从这些臃肿的代码中解脱出来。

首先看一下在Android Studio中引入ButterKnife步骤如下:

在项目上右键,选择Open Module Settings,如下:


选择APP->dependencies->“加号”->Library dependency如下:


输入butterknife如下:


选中目标点击OK,可以看出最新的ButterKnife已经升级到了8.2.1版本。还需要配置两个文件:

1.在project的build.gradle中


2.在module的build.gradle中



这时butterknife的环境就配置好了,可以运行测试一下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
? ?
android:layout_width="match_parent"
? ?
android:layout_height="match_parent">

? ?<TextView
? ? ? ?
android:id="@+id/tv1"
? ? ? ?
android:layout_width="match_parent"
? ? ? ?
android:layout_height="wrap_content"
? ? ? ?
android:gravity="center"
? ? ? ?
android:text="Hello World!"
? ? ? ?
android:textSize="18sp" />
</RelativeLayout>

MainActivity.java如下:

package com.example.administrator.myapplication;

import
android.os.Bundle;
import
android.support.v7.app.AppCompatActivity;
import
android.widget.TextView;

import
butterknife.BindView;
import
butterknife.ButterKnife;

public class
MainActivity extends AppCompatActivity {
? ?@BindView(R.id.tv1)
? ?TextView tv1;
? ?
@Override
? ?
protected void onCreate(Bundle savedInstanceState) {
? ? ? ?super.onCreate(savedInstanceState);
? ? ? ?
setContentView(R.layout.activity_main);
? ? ? ?
ButterKnife.bind(this);
? ? ? ?
tv1.setText("Hello ButterKnife");
? ?
}
}

调用@BindView传入TextView的id,然后在下面声明变量tv1,最后在onCreate方法中调用ButterKnife的bind方法绑定控件。

运行实例如下:

OK,届时butterknife引入成功!

下面看一下,引入Button的点击事件监听,布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center"
? ? ? ?
android:text="Hello World!"
? ? ? ?
android:textSize="18sp" />
? ?<Button
? ? ? ?
android:id="@+id/btn1"
? ? ? ?
android:text="BUTTON1"
? ? ? ?
android:layout_width="match_parent"
? ? ? ?
android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java:

@BindView(R.id.btn1)
Button btn1;
@OnClick(R.id.btn1)
public void test(View view) {
? ?Toast.makeText(MainActivity.this,"test",Toast.LENGTH_SHORT).show();
}

@Onclick传入Button的id为Button设置点击事件监听,运行实例如下:



谢谢关注我的微信公众号,觉得好可以分享到朋友圈哦.

请关注我的新浪微博:AndroidTip

CSDN博客:http://blog.csdn.net/yayun0516

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读