前言:
本人是一個只有幾個月工作經驗的碼小渣。這是我寫的第一篇博客,如有不足之處還請大家不要介意,還請大佬可以指出問題。
在這幾個月的實戰開發中自己也遇到了很多問題,真的是舉步艱難啊!!!
在實戰開發中遇到最多的就是findViewById我相信這也是很多和我一樣初入安卓行業的碼小渣遇到的最多的代碼。
現在來給碼小渣同志們分享一個非常實用的框架 “ButterKnife”
這是“聽着music睡”大佬給我推薦的。大家可以關注一下他,人特別好。我的這篇文章就是參考了他的文章。
廢話不多說上圖、上代碼。
代碼寫的不規范不要介意。
這是我平時寫的最多的,相信你們一開始也是這樣寫的。
像我這樣很多控件的時候代碼就顯得特別亂,不清晰。
今天我給大家介紹的ButterKnife框架就可以很好的解決這個問題。
使用ButterKnife框架
第一步:在項目中添加依賴
需要在app目錄下的 build.gradle文件中添加 :
implementation'com.jakewharton:butterknife:7.0.1'
第二步:在Android Studio 中安裝插件
首先在Android Studio主界面中選擇 "File" —— "Settings" —— 進入設置
然后找到 "Plugins" 搜索 "Android ButterKnife" 安裝插件 “Zelezny” 安裝完成后Android Studio 會自動重啟
下面就讓我們來體驗一下把。
新建一個新的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context="com.example.lenovo.myapplication.MainActivity">
<TextView
android:id="@+id/textView"
android:gravity="center"
android:text="你好"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/textView1"
android:gravity="center"
android:text="你是碼小渣嗎?"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/textView2"
android:gravity="center"
android:text="你好"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/textView3"
android:gravity="center"
android:text="你是第幾個看我博客的碼小渣"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/textView4"
android:gravity="center"
android:text="你好"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/textView5"
android:gravity="center"
android:text="謝謝你看我的博客"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
下面就開始在Activity中使用框架
新建一個Activity 在 Activity的中 右擊布局文件 選擇Generate...
出現新的對話框 點擊Generate Butterknife Injections
出現新的對話框 再這里我們可以選擇 布局文件中的控件
點擊 Confirm 會自動幫你生成注解 在onCreate()里多了一行 ButterKnife.bind(this);代碼
到這里 ButterKnife框架 就基本結束了 是不是很簡單而且幫你省了很多事
但是有一部分人在運行項目的時候可能會遇見和我一樣的問題
我也是翻遍度娘但是未曾找到解決方法 最后在大佬哪里得到解決辦法
在app目錄下的 build.gradle文件中的 defaultConfig 中加入下面的這些代碼 就OK了。
javaCompileOptions {
annotationProcessorOptions {
includeCompileClasspath = true
arguments = [moduleName: project.getName()]
}
}
運行成功。
到這里 ButterKnife 框架 就結束了是不是很神奇啊。
希望我的這篇文章能為你帶來幫助!!!
作者:碼小渣 文章地址:https://www.cnblogs.com/nc-183/p/9902442.html 本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責任的權利。