Kotlin library for Android

Overview

Download Build Status Average time to resolve an issue Android Arsenal

KAndroid

Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity.

Download

Download latest version with Gradle:

repositories {
    jcenter()
}

dependencies {
    compile 'com.pawegio.kandroid:kandroid:0.8.8@aar'
}

Usage

Binding views

// instead of findViewById(R.id.textView) as TextView
val textView = find<TextView>(R.id.textView)

Accessing ViewGroup children

/* instead of:
for (i in 0..layout - 1) {
    layout.getChildAt(i).visibility = View.GONE
}
*/
layout.views.forEach { it.visibility = View.GONE }

TextWatcher

/* instead of:
editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        before()
    }
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        onChange()
    }
    override fun afterTextChanged(s: Editable?) {
        after()
    }
}) */
editText.textWatcher {
    beforeTextChanged { text, start, count, after -> before() }
    onTextChanged { text, start, before, count -> onChange() }
    afterTextChanged { text -> after() }
}

SearchView extensions

/* instead of:
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextChange(q: String): Boolean {
        update(q)
        return false
    }
    
    override fun onQueryTextSubmit(q: String): Boolean {
        return false
    }
}) */
searchView.onQueryChange { query -> update(query) }

/* instead of:
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
    override fun onQueryTextChange(q: String): Boolean {
        return false
    }
    
    override fun onQueryTextSubmit(q: String): Boolean {
        update(q)
        return false
    }
}) */
searchView.onQuerySubmit { query -> update(query) }

SeekBar extension

/* instead of:
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
    override fun onStopTrackingTouch(seekBar: SeekBar) {

    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {

    }

    override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
        mediaPlayer.seekTo(progress)
    }

}) */
seekBar.onProgressChanged { progress, fromUser -> 
    if (fromUser) mediaPlayer.seekTo(progress) 
}

Using system services

// instead of getSystemService(Context.WINDOW_SERVICE) as WindowManager?
windowManager
// instead of getSystemService(Context.POWER_SERVICE) as PowerManager?
powerManager
// instead of getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificationManager
// instead of getSystemService(Context.USER_SERVICE) as UserManager?
userManager
// etc.

Toast messages

longToast("I'm long toast message!")
toast("Hi, I'm short one!")

longToast(R.string.my_string)
toast(R.string.my_string)

Layout inflater

// instead of LayoutInflater.from(context).inflate(R.layout.some_layout, null, false)
context.inflateLayout(R.layout.some_layout)
// or
context.inflateLayout(R.layout.some_layout, attachToRoot = true)

Using Intents

// instead of Intent(this, javaClass<SampleActivity>())
val intent = IntentFor<SampleActivity>(this)
// instead of startActivity(Intent(this, javaClass<SampleActivity>()))
startActivity<SampleActivity>()
// instead of startActivityForResult(Intent(this, javaClass<SampleActivity>()), REQUEST_CODE)
startActivityForResult<SampleActivity>(REQUEST_CODE)

Logging

// using javaClass.simpleName as a TAG
w("Warn log message")
e("Error log message")
wtf("WTF log message")
// using lambda log method
v { "Verbose log message" }
d { "Debug log message" }
i { "Info log message" }
// or with custom TAG
v("CustomTag", "Verbose log message with custom tag") 

Threading

// instead of Thread(Runnable { /* long execution */ }).start()
runAsync {
    // long execution
}

// delayed run (e.g. after 1000 millis)
// equals Handler().postDelayed(Runnable { /* delayed execution */ }, delayMillis)
runDelayed(1000) {
    // delayed execution
}

// run on Main Thread outside Activity
// equals Handler(Looper.getMainLooper()).post(Runnable { /* UI update */ })
runOnUiThread {
    // UI update
}

// delayed run on Main Thread
// equals Handler(Looper.getMainLooper()).postDelayed(Runnable { /* delayed UI update */ }, delayMillis)
runDelayedOnUiThread(5000) {
    // delayed UI update
}

From/To API SDK

// instead of if (Build.VERSION.SDK_INT >= 21) { /* run methods available since API 21 */ }
fromApi(21) {
    // run methods available since API 21
}

// instead of if (Build.VERSION.SDK_INT < 16) { /* handle devices using older APIs */ }
toApi(16) {
    // handle devices running older APIs
}
// or
// instead of if (Build.VERSION.SDK_INT <= 16) { /* handle devices using older APIs */ }
toApi(16, inclusive = true) {
    // handle devices running older APIs
}

Loading animation from xml

// instead of AnimationUtils.loadAnimation(applicationContext, R.anim.slide_in_left)
loadAnimation(R.anim.slide_in_left)

Animation listener

/*instead of:
animation.setAnimationListener(object : Animation.AnimationListener{
	override fun onAnimationStart(animation: Animation?) {
		onStart()
	}
	override fun onAnimationEnd(animation: Animation?) {
		onEnd()
	}
	override fun onAnimationRepeat(animation: Animation) {
		onRepeat()
	}
})*/

animation.animListener {
	onAnimationStart { onStart() }
	onAnimationEnd { onEnd() }
	onAnimationRepeat { onRepeat() }
}

Web intents with url validation

// instead of Intent(Intent.ACTION_VIEW, Uri.parse("http://github.com"))
WebIntent("http://github.com")

More

Under development so expect soon. Apps using KAndroid

(contact me or create new pull request to add your apps)

License

Copyright 2015-2017 Paweł Gajda

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Multiple toasts or toasts during dismissing

    Multiple toasts or toasts during dismissing

    Hello, At first, thank you for your job related library. But unfortunately I couldn't find the solution for cancel the toasts. It'll be a good feature in cases when I make multiple toasts or the activity/fragment dismissing and toast's showing in a same time. What do you think about it?

    opened by Papashkin 4
  • Change request: using non null types for system services

    Change request: using non null types for system services

    From the getSystemService method documentation: "@return The service or null if the name does not exist"

    So, if a name constant is used (and not a random string), the API guarantees to return a non-null object. So I think that the returned objects should have non-null types.

    opened by jakubvimn 3
  • checking permissions added

    checking permissions added

    Using example:

    if (isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
    	write()
    } else {
    	// request permission
    }
    
    if (isPermissionsGranted(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
    	readAndWrite()
    } else {
    	// request all permissions
    }
    
    opened by illuzor 2
  • Introduce KAnimator

    Introduce KAnimator

    This will fix #44.

    Introduce a new extension group for Animator class: KAnimator. Contains (at the moment) an extension function to simplify calls to Animator.addListener().

    opened by MrHadiSatrio 1
  • Any reason to have set minSdk ?

    Any reason to have set minSdk ?

    Please remove it, i don't think it's really necessary to have this lib minSDK dependent

    Error:Execution failed for task ':app:processDebugManifest'.
    > Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.pawegio.kandroid:kandroid:0.8.2] C:\Users\Scurab\.gradle\caches\transforms-1\files-1.1\kandroid-0.8.2.aar\704525ba697778b05fda2c8e22a64fbf\AndroidManifest.xml as the library might be using APIs not available in 15
      	Suggestion: use a compatible library with a minSdk of at most 15,
      		or increase this project's minSdk version to at least 16,
      		or use tools:overrideLibrary="com.pawegio.kandroid" to force usage (may lead to runtime failures)
    
    opened by jbruchanov 1
  • Change request: making runOnUiThread method conststent with the Android API method

    Change request: making runOnUiThread method conststent with the Android API method

    The API method https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) doesn't use Handler when the calling thread is UI, whereas the method runOnUiThread from here https://github.com/pawegio/KAndroid/blob/master/kandroid/src/main/kotlin/com/pawegio/kandroid/KThread.kt always uses Handler.

    I think that the inconsistency between these 2 methods may be confusing.

    opened by jakubvimn 1
  • Vals for check external storage readable/writable

    Vals for check external storage readable/writable

    I would like to propose two useful vals:

    val isExternalStorageWritable
        get() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
    
    val isExternalStorageReadable
        get() = Environment.MEDIA_MOUNTED_READ_ONLY == Environment.getExternalStorageState() || externalStorageWritable
    

    But I don`t know where to add them. I mean which file. Maybe create a new one?

    opened by illuzor 1
  • visible property for View

    visible property for View

    In my opinion it very useful. Boolean property much easier to use instead of VISIBLE/INVISIBLE/GONE. Personally, I never use INVISIBLE, but if somebody needs it, he can use existing visibility property.

    opened by illuzor 1
  • Failed to resolve: com.pawegio.kandroid:kandroid:0.8.8

    Failed to resolve: com.pawegio.kandroid:kandroid:0.8.8

    Issue is appeared when upgrading: Android Studio 3.6 -> 4.0 Gradle 3.6.3 -> 4.0.0 and -distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip +distributionUrl=https://services.gradle.org/distributions/gradle-6.1.1-all.zip

    opened by Andrey-Morenkov 4
  • Add names to lambda parameters

    Add names to lambda parameters

    eg. fun onTextChanged(listener: (text: CharSequence?, start: Int, before: Int, count: Int) -> Unit) { }

    this should allow to better code completion in IDE

    opened by igorwojda 0
  • `Environment.isExternalStorageWritable` not usable

    `Environment.isExternalStorageWritable` not usable

    The extension functions for android.os.Environment that is currently provided by KEnvironment.kt cannot be used without first creating an instance of Environment which isn't desirable because android.os.Environment is just meant as a utility class filled with static methods.

    To access the provided extension functions I have to write this:

    if (Environment().isExternalStorageWritable()) {
      …
    }
    

    That is, notice Environment() and not Environment which means I have to create an instance of Environment first before using it.

    It is currently not possible in Kotlin to provide static extension functions to existing java classes. See, https://discuss.kotlinlang.org/t/static-extension-methods-for-java-classes/2190

    Therefore the extension functions provided by KEnvironment.kt is not usable or practical. I would say either removing it or changing them into top-level functions instead.

    opened by jasonsparc 0
  • Feature request: modularization

    Feature request: modularization

    Currently all the extensions are in one library. This library has a dependency to appcompat. So if the library is used by a project that doesn't use appcompat, it will be automatically added (unless it's explicitly excluded). It would be good to divide the library to a set of libraries that contains extensions for each module, e.g.

    • android classes
    • support v4
    • appcompat

    Additionally, a no-code module could be created, which can contain dependencies to all the separate modules. It's the same approach that is currently used e.g. by Google Play Services.

    enhancement 
    opened by jakubvimn 1
Releases(v0.8.4)
Owner
Paweł Gajda
Android Developer
Paweł Gajda
A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

A somewhat copy past of Jetbrain's code from the kotlin plugin repo to make it humanly possible to test Intellij IDEA kotlin plugins that work on kotlin

common sense OSS 0 Jan 20, 2022
[Android Library] A SharedPreferences helper library to save and fetch the values easily.

Preference Helper A SharedPreferences helper library to save and fetch the values easily. Featured in Use in your project Add this to your module's bu

Naveen T P 13 Apr 4, 2020
Kotlin library for Android

KAndroid Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity. Download Downl

Paweł Gajda 890 Nov 13, 2022
🔓 Kotlin version of the popular google/easypermissions wrapper library to simplify basic system permissions logic on Android M or higher.

EasyPermissions-ktx Kotlin version of the popular googlesample/easypermissions wrapper library to simplify basic system permissions logic on Android M

Madalin Valceleanu 326 Dec 23, 2022
Android Spinner Dialog Library supported on both Java and Kotlin, Use for single or multi selection of choice

SpinnerDialog Android Spinner Dialog Library, Use for single or multi selection of choice Android UI Download To include SpinnerDialog in your project

Hamza Khan 55 Sep 15, 2022
A Kotlin library for reactive and boilerplate-free SharedPreferences in Android

KPreferences A Kotlin library for reactive and boilerplate-free Shared Preferences in Android. With KPreferences you can use Kotlin's marvelous delega

Mohamad Amin Mohamadi 19 Dec 16, 2020
The most complete and powerful data-binding library and persistence infra for Kotlin 1.3, Android & Splitties Views DSL, JavaFX & TornadoFX, JSON, JDBC & SQLite, SharedPreferences.

Lychee (ex. reactive-properties) Lychee is a library to rule all the data. ToC Approach to declaring data Properties Other data-binding libraries Prop

Mike 112 Dec 9, 2022
A Bluetooth kotlin multiplatform "Cross-Platform" library for iOS and Android

Blue-Falcon A Bluetooth "Cross Platform" Kotlin Multiplatform library for iOS, Android, MacOS, Raspberry Pi and Javascript. Bluetooth in general has t

Andrew Reed 220 Dec 28, 2022
A Kotlin Android library for content provider queries with reactive streams and coroutines.

Pickpocket An Android library for content provider queries with reactive streams and coroutines. Calendar Contacts SMS MMS Files/Media Call Log Bookma

Chris Basinger 27 Nov 14, 2022
A Kotlin Android library for heuristics evasion that prevents your code from being tested.

EvadeMe An Android library for heuristics evasion that prevents your code from being tested. User Instructions Add the maven repository to your projec

Chris Basinger 29 Dec 26, 2022
Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties

Easy lightweight SharedPreferences library for Android in Kotlin using delegated properties Idea Delegated properties in Kotlin allow you to execute a

null 25 Dec 27, 2022
Android AsyncTask wrapper library, written in Kotlin

KillerTask This is a Kotlin Android library to create async background tasks. Inspired by TinyTask, but more beautiful and easy to use for Kotlin Andr

Inaka 26 Oct 3, 2022
A Kotlin work manager library for Android with progress notifications and Hilt support.

Boot Laces A kotlin work manager library for Android that includes notifications and Hilt support. User Instructions Add the JitPack repository to you

Chris Basinger 35 Oct 8, 2022
Stateful is a Kotlin library which makes Android application development faster and easier.

Stateful Stateful is a Kotlin library which makes Android application development faster and easier. It helps you delete all the boilerplate code for

PicsArt 67 Oct 3, 2022
Android Library for requesting Permissions with Kotlin Coroutines or AndroidX LiveData

PEKO PErmissions with KOtlin Android Permissions with Kotlin Coroutines or LiveData No more callbacks, builders, listeners or verbose code for request

Marko Devcic 133 Dec 14, 2022
An Android Library that provides social login for 15 platforms within by RxJava2, Kotlin and Firebase Authentication.

RxSocialLogin The license information for logo is located at the bottom of the document. These instructions are available in their respective language

WindSekirun (wind.seo) 124 Nov 21, 2022
Kaffeine is a Kotlin-flavored Android library for accelerating development.

Kaffeine Kaffeine is a Kotlin-flavored Android library for accelerating development. Several Words of Caution Besides the obvious productivity advanta

Ragunath Jawahar 156 Nov 18, 2022
Koi, a lightweight kotlin library for Android Development.

Koi - A lightweight Kotlin library for Android Koi include many useful extensions and functions, they can help reducing the boilerplate code in Androi

Hello World 514 Nov 29, 2022
Kotpref - Android SharedPreferences delegation library for Kotlin

Kotpref Android SharedPreference delegation for Kotlin. Install repositories { mavenCentral() } dependencies { // core implementation 'co

Takao Chiba 684 Dec 22, 2022