KAndroid


Source link: https://github.com/pawegio/KAndroid

KAndroid

Kotlin library for Android providing useful extensions to eliminate boilerplate code in Android SDK and focus on productivity. Library is compatible with Kotlin 1.1.51 build.

Download

Download latest version with Gradle:

repositories {

  jcenter() 
}
  dependencies {

  compile 'com.pawegio.kandroid:kandroid:0.8.5@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. 

Resources

Wow, Android View Animation!

Lettrine is a library that let you display TextView with an initial first letter.

An Android time picker library.

CloudRail is a free software library which abstracts multiple APIs from different providers into a single and universal interface.

This library is a set of VIEWS (not Preferences) and is aimed to solve this problems:

  • Preferences look ugly on pre-lollipop.
  • Preferences are not flexible. For example, it can be problematic to embed them to another screen (especially for fragment-haters).
  • Preferences don't allow you to show custom selection dialogs.

A simple breadcrumb view based on the design support library's TabLayout.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes