android 封裝工具類(kotlin)

項目地址 github.com/damo2/commo…java

獲取applicationId

App 模塊AndroidManifest 添加android

<meta-data
         android:name="APPLICATION_ID"
         android:value="${applicationId}"/>
複製代碼

經過 applicationIdExt獲取applicationIdgit

打印日誌

loggergithub

//可選,日誌保存本地,在 application 添加, DiskLogAdapter 須要存儲權限
Logger.addLogAdapter(DiskLogAdapter())
//使用
logd("開始")
loge("異常")
複製代碼
吐司
toastInfo("信息")
複製代碼
json解析
//寫法1
val userBean = userJsonStr.gsonFromJsonExt<UserBean>()
val jsonStr = userBean.toJsonExt()

//寫法2
val message: MessageBean<ImageBean>  = GsonConvert.jsonToBean(jsonString, MessageBean.class, ImageBean.class)
var  bean :List<Bean>?  = GsonConvert.jsonToBeanList(jsonStr, Bean::class.java)
var  bean :BaseBean<SelectTypeBeam>?  = GsonConvert.fromJsonToBeanDataList(jsonStr, BaseBean::class.java, SelectTypeBeam::class.java)
複製代碼
圖片加載
imageLoader().load(context, "http://chuantu.biz/t6/345/1532056593x-1404817629.jpg", ivIcon,
                centerCrop = true,placeholder = R.drawable.ic_launcher)
複製代碼
SharedPreferences 保存信息

eg: 1.PreferenceNonNull 取值不能爲空 var isShowGuide: Boolean by PreferenceNonNull(context, ConstantsKey.KEY_IS_SHOW_GUIDE, false) //取值 isShowGuide //設置值 isShowGuide=truejson

2.Preference 取值可爲空
//注意 對象UserInfo 及裏面的對象都要實現Serializable
 var mUserInfoBean: UserInfo? by Preference<UserInfo>(context, "userinfo", UserInfo::class.java)
複製代碼
SDPathUtils 獲取目錄
//SD目錄
SDPathUtils.getSDCardPublicDir("xiaoyingying/log")
//緩存目錄
SDPathUtils.getSDCardPrivateCacheDir(context,"cacheFile")
複製代碼
EncryptUtils 加密解密
//加密
val dataEncrypt = EncryptUtils.instance.encrypt("啦啦啦123")
//解密
val dataDecrypt = EncryptUtils.instance.decrypt(dataEncrypt)
複製代碼
CommonAdapter使用
//kotlin
val adapter = CommonAdapter(this, R.layout.$itemLayoutId$, $data$, holderConvert = { holder, data, position, payloads ->

})
複製代碼

網絡請求

接口
LoginService裏面:
//地址帶有 https: 後 不會用 baseurl 了
@POST("https://www.dudulifo.com/user/phonelogin")
@FormUrlEncoded
fun login(@FieldMap map: HashMap<String, String>): Observable<BaseBean<UserInfo>>
複製代碼
初始化
object ApiManager {
    var apiService by NotNullSingle<ApiService>()
    //application 初始化
    fun initApiService() {
        apiService = RequestApiManager.instance.apply {
            initRetrofit({ clientBuilder ->
                //添加攔截器
            }, { retrofitBuilder ->
            }, ConstApi.BaseUrl)
        }.createService(ApiService::class.java)
    }
}
複製代碼
請求
//請求
ApiManager.apiService
                .update("1.0")
                .composeLife(getLifecycleSubject(), LifeCycleEvent.DESTROY)//結束時取消訂閱
                .composeDefault()//統一處理異常,請求後臺異常throw ApiException ,異常信息爲後臺給的異常內容
                .subscribeExtApi({
                    //成功返回
                    toastInfo(it.toString())
                }, { e ->
                    //異常,不傳默認toast ApiError的異常信息,添加此處理了 isToast 無效。
                    if (e is ApiException) {
                        //可根據後臺錯誤碼處理不一樣異常
                        logd("${e.code}")
                    }
                    toastInfo("更新失敗")
                }, {
                    //請求完成
                }, isShowLoad = true,// 是否顯示進度框
                        context = activity,//isShowLoad 爲true時必傳
                        isToast = true//是否toast異常,處理了異常時無效
                )

 //文件下載
 RequestFileManager.downloadFile(
                     "http://wangru.oss-cn-qingdao.aliyuncs.com/test/erp-v1.0.0-20190404.apk",
                     StorageUtils.getPublicStoragePath("test/erp.apk"),
                     { file -> Toast.makeText(applicationContext, "下載成功${file.name}", Toast.LENGTH_SHORT).show() },
                     { e -> Toast.makeText(applicationContext, "下載失敗${e.message}", Toast.LENGTH_SHORT).show() },
                     { totalLength, contentLength, done ->
                         Logger.d("totalLength=$totalLength contentLength=$contentLength")
                     });
  //文件上傳
  RequestFileManager.uploadFileByKey(
                      "http://www.wxjishu.com:9999/file/upload",
                      "file",
                      File(StorageUtils.getPublicStoragePath("test/wanban.apk")),
                      { str -> Logger.d("上傳結果=$str") },
                      { e -> Logger.d("異常=$e") },
                      { progress,total -> Logger.d("up=$progress total=$total") }
              )
複製代碼

RxBus使用

發送方:
RxBus.post(new User("張三"))
複製代碼
接收方:
RxBus.toFlowable().subscribe { event ->
        if (event is DownApkEvent) {
        //todo same thing
        }
 }.apply {
        //todo 結束時取消監聽
 }
複製代碼

弱引用

private var activity: Activity? by Weak()
複製代碼

只能賦值一次,且不能爲空

var context by NotNullSingle<Context>()
複製代碼




多個判空

val num1: Int? = null
val num2: Int? = 2
ifNotNull(num1, num2) { num1a, num2a ->
    //都不爲空才執行
    print(num1a + num2a)
}
複製代碼

防止快速點擊

tvAnko.setOnClickExtNoFast {
    startActivity<AnkoActivity>()
}
複製代碼

限制最多輸入字數

edtInput.limitLengthExt(5,{ toastInfo("最多輸入字數爲5")})
複製代碼

單例

//沒有參數 (或者使用 lazy 委託)
class Manager {
    companion object : SingleHolder<Manager>(::Manager)
}
//使用
Manager.getInstance()

//一個參數
class Manager(context: Context) {
    companion object : SingleHolder1<Manager, Context>(::Manager)
    init {
        //使用context 初始化
    }
}
//使用
Manager.getInstance(context)
複製代碼
註解
@KeepNotProguard
class User(var name:String)//添加註解不混淆
複製代碼
日期
val date = Date()       //如今時間

    val beforeDay = date - 1    //前一天
    val lastDay = date + 1      //後一天

    val beforeHour = date - hour(1)     //前一個小時
    val lastHour = date + month(1)       //後一個月
    val beforeHour = date - minute(1)     //前一分鐘
    
    val isBefore = beforeDay < date     //比較大小
    
    date++      //本月的最後一天
    date--      //本月的第一天
    
    if(date > beforeDay){}   //比較日期
複製代碼




自定義view

點擊倒計時
<com.app.common.widget.CountdownButton
    android:id="@+id/btnGetCode"
    android:layout_width="110dp"
    android:layout_height="30dp"
    android:padding="0dp"
    android:textSize="12sp"
    android:textColor="#FFFFFF"
    android:text="獲取驗證碼"
    app:cb_downFormat="%s 秒"
    app:cb_endTxt="從新獲取"
    app:cb_totalTime="30000"
    app:cb_bg="@drawable/getcode_button"
    app:cb_isExitTiming="true"
    />
        
<!--getcode_button-->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#ff80cbc4" />
            <corners android:radius="50dp" />
        </shape>
    </item>
    <item android:state_enabled="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/common_textgray" />
            <corners android:radius="50dp" />
        </shape>
    </item>
</selector>
複製代碼
圓角view

RoundButtonView、RoundFrameLayout、RoundLinearLayout、RoundRelativeLayout、RoundTextView 相同設置api

//圓角button
<com.app.common.widget.round.RoundButtonView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="0dp"
        android:padding="8dp"
        android:text="圓角"
        android:textColor="#888888"
        app:backgroundColor="#D1C4E9"
        app:backgroundPressColor="#9575CD"
        app:borderColor="#81D4FA"
        app:borderPressColor="#0277BD"
        app:borderSize="0.5dp"
        app:isRippleEnable="false"
        app:radius="4dp"
        app:textPressColor="#FFFFFF"
        />
 //圓形圖片
<com.app.common.widget.round.RoundImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_test1"
        app:borderColor="#81D4FA"
        app:borderSize="8dp"
        />
複製代碼


擴展屬性和方法

代碼
工具類緩存

Activity 擴展屬性和方法
屬性和方法 描述
Activity.screenWidthExt 屏幕寬
Activity.screenHeightExt 屏幕高
Activity.statusBarHeightExt 狀態欄高度
Activity.navigationBarHeightExt 導航欄高度
Activity.navigationBarWidthExt 橫屏狀態下導航欄的寬度
Activity.activityRootExt 獲取activity的根view
Activity.hasNavBarExt 是否有導航欄
Activity.statusHind() 隱藏狀態欄
Activity.statusTranslucent() 沉浸式狀態欄
Activity.viewIsVisibleExt(view) view是否在屏幕中可見
Context 擴展屬性和方法
屬性和方法 描述
Context.versionCodeExt 版本號
Context.versionNameExt 版本名
Context.appNameExt 項目名
Context.applicationIdExt applicationId
Context.androidIDExt 設備惟一id
Context.screenWidthExt 屏幕寬
Context.screenHeightExt 屏幕高
Context.isAppRunningForegroundExt() 是否運行在前臺
Context.checkDeviceHasNavigationBarExt() 是否有虛擬鍵盤
Context.getUriFromFileExt(file,applicationId) 文件生成Uri
Context.getActivityExt() 獲取Activity
Context.getAppIconDrawableExt(packageName) 獲取App圖標
Context.dp2px(dp) dp轉px
Context.sp2px(sp) sp轉px
Context.getColorExt(id[,theme]) 資源id獲取顏色
Context.getColorStateListExt(id[,theme]) 資源id獲取顏色
Context.getNetWorkTypeNameExt() 獲取當前的網絡類型(WIFI,2G,3G,4G)
Context.is4GExt() 判斷網絡是不是4G
Context.isWifiExt() 判斷wifi是否鏈接
String 擴展屬性和方法
屬性和方法 描述
String.equalsExt(str,isIgnoerNull) 是否相等
String.isEmailExt() 是不是郵箱
String.isPasswordHalfAngleExt() 是不是密碼半角(全部英文字符英文符號)
String.setColorExt(color) String 設置顏色
String.getNumExt(default) 獲取String裏面的數字
String.toIntExt(default) String轉int失敗
View 擴展屬性和方法
屬性和方法 描述
View.widthExt() view 寬
View.heightExt() view 高
View.setOnClickExtNoFast(time,block: (view: View) -> Unit) View.防止快速點擊
View.setMarginExt(left,top,right,bottom) 設置 Margin
View.setPaddingExt(left,top,right,bottom) 設置 Padding
View.setWidthHeightExt(width,height) 設置寬高
View.getActivityExt() 獲取 activity
View.toBitmapExt() view轉成bitmap
EditText 擴展屬性和方法
屬性和方法 描述
EditText.inhibitInputSpaceExt() 禁止輸入空格
EditText.limitLengthExt(length,outCallback) 限制輸入長度
EditText.setOnlyDecimalExt(isShow) 只能輸入數字和小數點,小數點只能1個且小數點後最多隻能2位
EditText.setPwdShowOrHindExt() 設置密碼顯示或隱藏
File 擴展屬性和方法
屬性和方法 描述
File.headerExt 獲取文件頭
File.metadataExt 文件類型
File.isImageExt 是不是圖片
File.sizeExt 獲取文件的大小
String.filenameExt 文件名字帶後綴
String.filenameNoExtensionExt 文件名字不帶後綴
String.fileExtensionExt 文件後綴
File.appendExt(txt,isCreate) 向文件中追加文本
File.getVideoInfoExt((duration: Int, width: Int, height: Int) -> Unit) 獲取視頻信息

參考及使用

圓角view https://github.com/H07000223/FlycoRoundView
通用adapter https://github.com/hongyangAndroid/baseAdapter
字體對齊的TextView  https://github.com/androiddevelop/AlignTextView
日誌 https://github.com/orhanobut/logger
複製代碼

項目地址: github.com/damo2/commo…bash

相關文章
相關標籤/搜索