Giter Site home page Giter Site logo

lulululbj / androidutilcodektx Goto Github PK

View Code? Open in Web Editor NEW
346.0 7.0 35.0 9.23 MB

Kotlin Android Util Code

Home Page: https://juejin.im/post/5d2adf215188252b13288942

License: Apache License 2.0

Kotlin 98.04% Java 1.96%
kotlin kotlin-library ktx android utils

androidutilcodektx's Introduction

AndroidUtilCodeKTX ! 专注提升 Android 开发效率 !

该类库利用 Kotlin 语言特性合理封装了 Android 开发中的常用操作,同时也收集了开发过程中的常用工具类。 旨在做同样的事情,写最少的代码,提升开发效率。

Change log

Use

implementation 'luyao.util.ktx:AndroidUtilKTX:0.0.5'

最新版本将第一时间用在我的另外两个开源项目,wanandroidBox,欢迎关注 !

APIS (keep updating...)


FragmentActivity.request(vararg permissions: String, callbacks: PermissionsCallbackDSL.() -> Unit)
Activity.startKtxActivity(
    flags: Int? = null,
    extra: Bundle? = null,
    value: Pair<String, Any>? = null,
    values: Collection<Pair<String, Any>?>? = null
) 

fun <reified T : Activity> Activity.startKtxActivityForResult(
    requestCode: Int,
    flags: Int? = null,
    extra: Bundle? = null,
    value: Pair<String, Any>? = null,
    values: Collection<Pair<String, Any>?>? = null
) 

Fragment.startKtxActivity()
Fragment.startKtxActivityForResult()
Context.startKtxActivity
Activity.hideKeyboard()
Activity.showKeyboard(et: EditText)
Activity.hideKeyboard(view: View)
Context.versionName: String
Context.versionCode: Long
Context.getAppInfo(apkPath: String): AppInfo
Context.getAppInfos(apkFolderPath: String): List<AppInfo>
Context.getAppSignature(packageName: String = this.packageName): ByteArray?
Context.isPackageInstalled(pkgName: String)
ByteArray.aesEncrypt(key: ByteArray, iv: ByteArray, cipherAlgotirhm: String = AES_CFB_NOPADDING): ByteArray
ByteArray.aesDecrypt(key: ByteArray, iv: ByteArray, cipherAlgotirhm: String = AES_CFB_NOPADDING): ByteArray 
File.aesEncrypt(key: ByteArray, iv: ByteArray, destFilePath: String): File?, cipherAlgotirhm: String = AES_CFB_NOPADDING)
File.aesDecrypt(key: ByteArray, iv: ByteArray, destFilePath: String): File?, cipherAlgotirhm: String = AES_CFB_NOPADDING)
initAESKey(size: Int): ByteArray
initCipher(mode: Int, key: ByteArray, iv: ByteArray, cipherAlgotirhm: String): Cipher
fromM()
beforeM()
fromN()
beforeN()
fromO()
beforeO()
fromP()
beforeP()
fromSpecificVersion(version: Int)
beforeSpecificVersion(version: Int)
Context.dp2px(dp: Int)
Context.px2dp(px: Int)
View.dp2px(dp: Int)
View.px2dp(px: Int)
Context.screenWidth
Context.screenHeight
Context.copyToClipboard(label: String, text: String)
Context.checkAccessbilityServiceEnabled(serviceName: String)
Any?.notNull(f: () -> T, t: () -> T): T
Context.isRTLLayout
fun isOnMainThread()
Drawable.convertToBitmap()
File.canListFiles
File.totalSize
File.formatSize
File.mimeType
File.listFiles(isRecursive: Boolean = false, filter: ((file: File) -> Boolean)? = null)
File.writeText(append: Boolean = false, text: String, charset: Charset = Charsets.UTF_8)
File.writeBytes(append: Boolean = false, bytes: ByteArray)
File.moveTo(destFile: File, overwrite: Boolean = true, reserve: Boolean = true)
File.moveToWithProgress(
    destFolder: File,
    overwrite: Boolean = true,
    reserve: Boolean = true,
    func: ((file: File, i: Int) -> Unit)? = null)
File.rename(newName: String)
File.rename(newFile: File)
ByteArray.hash(algorithm: Hash): String
String.hash(algorithm: Hash, charset: Charset = Charset.forName("utf-8")): String
ByteArray.md5Bytes(): ByteArray
ByteArray.md5(): String
String.md5(charset: Charset = Charset.forName("utf-8")): String
ByteArray.sha1Bytes(): ByteArray
ByteArray.sha1(): String
String.sha1(charset: Charset = Charset.forName("utf-8")): String
ByteArray.sha224Bytes(): ByteArray
ByteArray.sha224(): String
String.sha224(charset: Charset = Charset.forName("utf-8")): String
ByteArray.sha256Bytes(): ByteArray
ByteArray.sha256(): String
String.sha256(charset: Charset = Charset.forName("utf-8")): String
ByteArray.sha384Bytes(): ByteArray
ByteArray.sha384(): String
String.sha384(charset: Charset = Charset.forName("utf-8")): String
ByteArray.sha512Bytes(): ByteArray
ByteArray.sha512(): String
String.sha512(charset: Charset = Charset.forName("utf-8")): String
File.hash(algorithm: Hash = Hash.SHA1): String
Context.getAppInfoIntent(packageName: String = this.packageName): Intent
Context.goToAppInfoPage(packageName: String = this.packageName)
Context.getDateAndTimeIntent(): Intent
Context.goToDateAndTimePage()
Context.getLanguageIntent()
Context.goToLanguagePage() 
Context.getInstallIntent(apkFile: File): Intent?
Context.goToAccessibilitySetting()
Context.installApk(apkFile: File)
Context.openBrowser(url: String)
Context.openInAppStore(packageName: String = this.packageName)
Context.openApp(packageName: String)
Context.uninstallApp(packageName: String)
Context.sendEmail(email: String, subject: String?, text: String?) 
pushActivity(activity: Activity)
popActivity(activity: Activity)
finishCurrentActivity()
finishActivity(activity: Activity)
 finishActivity(clazz: Class<*>)
finishAllActivity()
text(
    text: CharSequence,
    isNewLine: Boolean = true,
    textSize: Int = -1,
    fontFamily: String = "",
    customTypeFace: Typeface? = null,
    isDp: Boolean = true,
    fontProportion: Float = -1f,
    xFontProportion: Float = -1f,
    lineHeight: Int = -1,
    foregroundColor: Int = -1,
    backgroundColor: Int = -1,
    alignment: Layout.Alignment? = null,
    isBold: Boolean = false,
    isStrikethrough: Boolean = false,
    isUnderline: Boolean = false,
    isItalic: Boolean = false,
    isBoldAndItalic: Boolean = false,
    isSuperscript: Boolean = false,
    isSubscript: Boolean = false,
    first: Int = 0,
    rest: Int = 0,
    quoteColor: Int = -1,
    quoteStripeWidth: Int = STANDARD_STRIPE_WIDTH_PX,
    quoteGapWidth: Int = STANDARD_GAP_WIDTH_PX,
    bulletColor: Int = -1,
    bulletRadius: Int = STANDARD_BULLET_RADIUS,
    bulletGapWidth: Int = STANDARD_GAP_WIDTH_PX,
    clickSpan: ClickableSpan? = null,
    url: String? = null,
    blurRadius: Float = -1f,
    blurStyle: BlurMaskFilter.Blur = BlurMaskFilter.Blur.NORMAL
): KtxSpan 
    
image(
    resId: Int,
    verticalAlignment: Int = KtxImageSpan.ALIGN_MIDDLE,
    marginLeft: Int = 0,
    marginRight: Int = 0,
    offsetY: Int = 0,
    fontWidthMultiple: Float = -1f
) 

blockLine(@Px height: Int, addBlockAlways: Boolean = false)
SearchView.queryTextListener(listener: KtxQueryTextLister.() -> Unit)
SeekBar.onProgressBarChanged(callback: (Int, Boolean) -> Unit)
TextView.textWatcher(watcher: KtxTextWatcher.() -> Unit)
ViewPager.onPageSelected(pageChangedAction: (newPosition: Int) -> Unit)
String.logv(tag: String = TAG)
String.logd(tag: String = TAG)
String.logi(tag: String = TAG)
String.logw(tag: String = TAG)
String.loge(tag: String = TAG)
<T> Context.putSpValue(key: String, value: T, name: String = packageName)
<T> Activity.putSpValue(key: String, value: T, name: String = packageName)
<T> Context.getSpValue(key: String, default: T, name: String = packageName ): T
<T> Activity.getSpValue(key: String, default: T, name: String = packageName): T
String.areDigitsOnly()
Context.windowManager
Context.clipboardManager
Context.layoutInflater
Context.activityManager
Context.powerManager
Context.alarmManager
Context.notificationManager
Context.keyguardManager
Context.locationManager
Context.searchManager
Context.storageManager
Context.vibrator
Context.connectivityManager
Context.wifiManager
Context.audioManager
Context.mediaRouter
Context.telephonyManager
Context.sensorManager
Context.subscriptionManager
Context.carrierConfigManager
Context.inputMethodManager
Context.uiModeManager
Context.downloadManager
Context.batteryManager
Context.jobScheduler
Context.accessibilityManager
Context.toast(content: String, duration: Int = Toast.LENGTH_SHORT)
Context.toast(@StringRes id: Int, duration: Int = Toast.LENGTH_SHORT)
Context.longToast(content: String)
Context.longToast(@StringRes id: Int)
Any.toast(context: Context, content: String, duration: Int = Toast.LENGTH_SHORT)
Any.toast(context: Context, @StringRes id: Int, duration: Int=Toast.LENGTH_SHORT) 
Any.longToast(context: Context, content: String)
Any.longToast(context: Context, @StringRes id: Int)
ByteArray.toHexString() : 字节数组转十六进制字符串
View.visible()
View.invisible()
View.gone()
View.reverseVisiblity(needGone: Boolean = true)
View.changeVisible(visible: Boolean, needGone: Boolean = true)
var View.isVisible: Boolean
var View.isInvisible: Boolean
var View.isGone: Boolean
View.setPadding(@Px size: Int)
View.postDelayed(delayInMillis: Long, crossinline action: () -> Unit): Runnable
View.toBitmap(config: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap
RecyclerView.itemPadding(padding:Int)
RecyclerView.itemPadding(top: Int, bottom: Int, left: Int = 0, right: Int = 0)
TextView.notEmpty(f: TextView.() -> Unit, t: TextView.() -> Unit)
View.onGlobalLayout(crossinline callback: () -> Unit)
fun View.afterMeasured(crossinline callback: View.() -> Unit)

Others

  1. KtxHandler : 跟随组件生命周期自动处理的 Handler
  2. KtxAppLifeObserver : 应用前后台监听

androidutilcodektx's People

Contributors

lulululbj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

androidutilcodektx's Issues

这个崩

java.lang.RuntimeException: Unable to start activity ComponentInfo{luyao.ktx/luyao.util.ktx.mvvm.MvvmActivity}: java.lang.IllegalStateException: You can consumeRestoredStateForKey only after super.onCreate of corresponding component
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2883)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2958)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6653)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Caused by: java.lang.IllegalStateException: You can consumeRestoredStateForKey only after super.onCreate of corresponding component
at androidx.savedstate.SavedStateRegistry.consumeRestoredStateForKey(SavedStateRegistry.java:77)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:65)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:177)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:145)
at luyao.util.ktx.base.BaseVMActivity.initVM(BaseVMActivity.kt:24)
at luyao.util.ktx.base.BaseVMActivity.onCreate(BaseVMActivity.kt:17)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2836)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2958) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6653) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 

Val cannot be reassigned

fun Context.copyToClipboard(label: String, text: String) {
val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText(label, text)
cm.primaryClip = clipData
}

最后一行报错

异常捕捉

mException.value = e 在案例中onError方法还是接收不到

我用的一些扩展

1、Intent 获取参数,以 String 为例:

fun Activity.extraString(key: String, default: String = ""): Lazy<String> = lazy {
    intent?.extras?.getString(key) ?: default
}

示例:

 private val vinCode: String by extraString(DATA_VIN_CODE)

2、Boolean 的扩展,链式调用:

object Otherwise : BooleanExt<Nothing>()
class TransferData<T>(val data: T) : BooleanExt<T>()

inline fun <T> Boolean.yes(block: () -> T): BooleanExt<T> = when {
    this -> TransferData(block.invoke())
    else -> Otherwise
}

inline fun <T> BooleanExt<T>.otherwise(block: () -> T): T = when (this) {
    is Otherwise -> block.invoke()
    is TransferData -> this.data
}

示例:

isNotEmpty().yes {

}.otherwise {

}

这样嵌套用多了代码又丑又难阅读😂

3、view 防止多次点击

  • 通过时间判断
fun View.singleClick(clickEventFun: () -> Unit) {
    this.setOnClickListener {
        if (Utils.isFastClick()) {
            clickEventFun.invoke()
        }
    }
}
  • 使用 rxjava 去重(目前已废弃),
@SuppressLint("CheckResult")
@Deprecated("memory leak")
fun View.singleClick(
    intervalDuration: Long = 1,
    unit: TimeUnit = TimeUnit.SECONDS,
    eventFun: () -> Unit
) {
    Observable
        .create(object : ObservableOnSubscribe<View> {
            lateinit var mEmitter: ObservableEmitter<View>

            init {
                [email protected] {
                    mEmitter.onNext(it)
                }
            }

            override fun subscribe(emitter: ObservableEmitter<View>) {
                mEmitter = emitter
            }
        })
        .throttleLast(intervalDuration, unit)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe {
            eventFun()
        }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.