KtKit 是用 Kotlin 语言编写的工具库,包含了项目中常用的一系列工具

Overview

KtKit

KtKit 小巧而实用,用 Kotlin 语言编写的工具库(长期更新中)
KtKit 在线阅读:https://ktkit.hi-dhl.com

       

如果图片无法查看,请点击这里查看 图例

关于 KtKit

KtKit 是用 Kotlin 语言编写的工具库,包含了项目中常用的一系列工具,是 Jetpack ktx 系列的补充,涉及到了很多从 Kotlin 源码、Jetpack ktx、anko 等等知名的开源项目中学习的技巧,包含了 Kotlin 委托属性、高阶函数、扩展函数、内联、注解的使用等等,再次感谢以下项目提供的思路。

但是目前还不是很完善,正在陆续将一些常用的功能,结合着 Kotlin 的高级函数的特性,不仅让代码可读性更强,使用更加简单,而且还可以帮助我们解决项目中常见的问题。

Download

正式版本: 此版本包含稳定版本的 API

Maven Central

// Project 级别的 `build.gradle`
allprojects {
    repositories {
        mavenCentral()
    }
}

// 模块级 `build.gradle`
dependencies {
    implementation "com.hi-dhl:ktkit:${ktkitVersion}"
}

快照版本: 此版本包含最新的 API,版本号点击 snapshots 前往查看

// Project 级别的 `build.gradle`
allprojects {
    repositories {
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
    }
}

// 模块级 `build.gradle`
dependencies {
    implementation "com.hi-dhl:ktkit:${ktkitVersion}"
}

如果这个仓库对你有帮助,请在仓库右上角帮我 star 一下,非常感谢你的支持,同时也欢迎你提交 PR ❤️ ❤️ ❤️

项目中引用了 spotless 插件,执行 ./gradlew spotlessApply 会将 Java 、Kotlin 、xml 、gradle 、md 、gitignore 等等文件按照官方标准去格式化。这也是 Google 提交代码的时候,推荐的方式。

如何使用

在 Activity 或者 Fragment 中获取传递过来的参数

以下两种方式根据实际情况使用即可

// 方式一: 不带默认值
private val userPassword by intent(KEY_USER_PASSWORD)

// 方式二:带默认值:如果获取失败,返回一个默认值
private val userName by intent(KEY_USER_NAME) {
    "公众号:ByteCode"
}

Activity 之间跳转 及传递参数

以下两种方式根据实际情况使用即可

( KEY_USER_NAME to "ByteCode", KEY_USER_PASSWORD to "1024" ) ">
// 方式一
context.startActivity {
    arrayOf(
            KEY_USER_NAME to "ByteCode",
            KEY_USER_PASSWORD to "1024",
            KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl")
    )
}

// 方式二
context.startActivity(
        KEY_USER_NAME to "ByteCode",
        KEY_USER_PASSWORD to "1024"
)

Activity 之间跳转 及传递参数 和 回传结果 以下两种方式根据实际情况使用即可

(KEY_REQUEST_CODE) { arrayOf( KEY_USER_NAME to "ByteCode", KEY_USER_PASSWORD to "1024", KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl") ) } ">
// 方式一
context.startActivityForResult(KEY_REQUEST_CODE,
        KEY_USER_NAME to "ByteCode",
        KEY_USER_PASSWORD to "1024",
        KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl")
)

// 方式二
context.startActivityForResult(KEY_REQUEST_CODE) {
    arrayOf(
            KEY_USER_NAME to "ByteCode",
            KEY_USER_PASSWORD to "1024",
            KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl")
    )
}

回传结果

// 方式一
setActivityResult(Activity.RESULT_OK) {
   arrayOf(
            KEY_RESULT to "success"
    )
}
                    
// 方式二
setActivityResult(
        Activity.RESULT_OK,
        KEY_RESULT to "success",
        KEY_USER_NAME to "ByteCode"
)

Fragment 跳转 及 传递参数

// 方式一
fun newInstance1(): Fragment {
    return LoginFragment().makeBundle(
            ProfileActivity.KEY_USER_NAME to "ByteCode",
            ProfileActivity.KEY_USER_PASSWORD to "1024",
            ProfileActivity.KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl")
    )
}

// 方式二
fun newInstance2(): Fragment {
    return LoginFragment().makeBundle {
        arrayOf(
                KEY_USER_NAME to "ByteCode",
                KEY_USER_PASSWORD to "1024",
                KEY_PEOPLE_PARCELIZE to PeopleModel("hi-dhl")
        )
    }
}

一行代码实现点击事件,避免内存泄露

KtKit 提供了常用的三个 API:单击事件、延迟第一次点击事件、防止多次点击

单击事件

view.click(lifecycleScope) { showShortToast("公众号:ByteCode" }

延迟第一次点击事件

// 默认延迟时间是 500ms
view.clickDelayed(lifecycleScope){ showShortToast("公众号:ByteCode" }

// or
view.clickDelayed(lifecycleScope, 1000){ showShortToast("公众号:ByteCode") }

防止多次点击

// 默认间隔时间是 500ms
view.clickTrigger(lifecycleScope){ showShortToast("公众号:ByteCode") }

// or
view.clickTrigger(lifecycleScope, 1000){ showShortToast("公众号:ByteCode") }

更多 API 使用方式点击这里前往查看 在线文档

联系我

  • 个人微信:hi-dhl
  • 公众号:ByteCode,包含 Jetpack ,Kotlin ,Android 10 系列源码,译文,LeetCode / 剑指 Offer / 多线程 / 国内外大厂算法题 等等一系列文章


最后推荐我一直在更新维护的项目和网站:

  • 计划建立一个最全、最新的 AndroidX Jetpack 相关组件的实战项目 以及 相关组件原理分析文章,正在逐渐增加 Jetpack 新成员,仓库持续更新,欢迎前去查看:AndroidX-Jetpack-Practice

  • LeetCode / 剑指 offer / 国内外大厂面试题 / 多线程 题解,语言 Java 和 kotlin,包含多种解法、解题思路、时间复杂度、空间复杂度分析

  • 最新 Android 10 源码分析系列文章,了解系统源码,不仅有助于分析问题,在面试过程中,对我们也是非常有帮助的,仓库持续更新,欢迎前去查看 Android10-Source-Analysis

  • 整理和翻译一系列精选国外的技术文章,每篇文章都会有译者思考部分,对原文的更加深入的解读,仓库持续更新,欢迎前去查看 Technical-Article-Translation

  • 「为互联网人而设计,国内国外名站导航」涵括新闻、体育、生活、娱乐、设计、产品、运营、前端开发、Android 开发等等网址,欢迎前去查看 为互联网人而设计导航网站

License

You might also like...
Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.
Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.

Kotlin Academy Mis experimentos con Kotlin para JetBrains donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema. Acerca de

Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto Kotlin Collections Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da

Kotlin-GraphQL-Apollo - Sencillo cliente para consumir una API GraphQL con Apollo usando Kotlin
Kotlin-GraphQL-Apollo - Sencillo cliente para consumir una API GraphQL con Apollo usando Kotlin

Kotlin GraphQL Apollo Sencillo cliente para consumir una API GraphQL con Apollo

DS-for-Kotlin - Some classic data sturctures write in kotlin for fun

DS-for-Kotlin Just write some classic data structure by kotlin during my leisure

Account-hexa-service-kotlin - Microservice with Kotlin using Hexagonal architecture

Microservice Construindo microservice de conta para fins Didáticos. Objetivos Cr

Akka-in-action-kotlin - Accompanying source code for Akka in Action by Kotlin

Akka実践バイブル Kotlin版サンプルコード ( Accompanying source code for Akka in Action by Kotli

Kotlin-phoenix - A set of tools aimed to bridge Phoenix with the Kotlin Multiplatform world

Kotlin Phoenix This project is aimed to allow developers to work with Phoenix Ch

Comments
  • 跟DataStore有冲突

    跟DataStore有冲突

    app.gradle
    
       plugins {
        id 'com.android.application'
        id 'kotlin-android'
        id 'kotlin-kapt'
        id 'dagger.hilt.android.plugin'
        id 'androidx.navigation.safeargs.kotlin'
        id 'kotlin-parcelize'
        id "com.google.protobuf" version "0.8.12"
    }
    
     //DataStore
        implementation "androidx.datastore:datastore:1.0.0"
        implementation "androidx.datastore:datastore-preferences:1.0.0"
    
    protobuf {
        protoc {
            artifact = "com.google.protobuf:protoc:3.14.0"
        }
    
        // Generates the java Protobuf-lite code for the Protobufs in this project. See
        // https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
        // for more information.
        generateProtoTasks {
            all().each { task ->
                task.builtins {
                    java {
                        option 'lite'
                    }
                }
            }
        }
    }
    
    user_info.proto
    
    syntax = "proto3";
    
    option java_package = "com.signcc.adoperations.datastore";
    option java_multiple_files = true;
    
    message UserInfo {
      string realName = 1;
      string se = 2;
      string nickname = 3;
      string userMobile = 4;
      string userName = 5;
      string userId = 6;
      int32 userStatus = 7;
    }
    

    然后添加依赖就会导致编译失败

    def ktkitVersion = "1.0.2"
    implementation "com.hi-dhl:ktkit:$ktkitVersion"
    
    opened by woitaylor 4
  • ./gradlew spotlessApply 命令运行不了

    ./gradlew spotlessApply 命令运行不了

    现象

    在执行 ./gradlew spotlessApply 这个命令的时候提示 Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain

    原因

    估计是 .gitignore 文件中将 jar 包排除在版本管理外导致项目中根目录下的 gradle 目录中缺失了 gradle-wrapper.jar 而出现的运行错误

    处理

    拷了一份 gradle-wrapper.jar 到该目录下后运行成功,建议将它添加回去。

    opened by ZakAnun 2
Owner
Jack Deng
公众号:ByteCode,致力于分享最新技术原创文章,涉及 Kotlin 、Jetpack 、译文 、系统源码 、 LeetCode / 剑指 Offer / 多线程 / 国内外大厂算法题 等等一系列文章。如果你同我一样喜欢 coding,一起来学习,期待与你一起成长...
Jack  Deng
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
Kotlin TodoMVC – full-stack Kotlin application demo

Kotlin full stack TodoMVC This project is an example implementation of the TodoMVC app written in Kotlin. More specifically, it's the Kotlin port of t

Gyula Voros 22 Oct 3, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
Kotlin Leaning Notes from Udacity Course | Kotlin Bootcamp for Programmers by Google

Kotlin Beginners Notes These are all personal notes taken from the Udacity Course (ud9011) of Kotlin Bootcamp for Programmers by Google as well as oth

Süha Tanrıverdi 34 Dec 10, 2022
Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Simon Vergauwen 50 Dec 30, 2022
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Oguzhan 18 Apr 21, 2022
A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Dario Mungoi 7 Sep 17, 2022