AndroidKotlinCommons


Source link: https://github.com/dewarder/Android-Kotlin-Commons

Android-Kotlin-Commons

Small library that contains common extensions for Android. Aims:

  • Provide the shortest way to do things
  • Reduce count of "Compat" and "Utils" classes
  • Remove boilerplate code

Getting started

Add library as dependency to your build.gradle.

compile 'com.dewarder:akommons:0.0.4' 

Features

Views

Visibility

override fun onCreate(savedInstanceState: Bundle) {

  ...
  firstView.isVisible = true
  secondView.isVisible = false
  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  firstView.visibility = View.VISIBLE
  secondView.visibility = View.GONE
  ... 
}

Auto-casting

private lateinit var linearLayout: LinearLayout
override fun onCreate(savedInstanceState: Bundle) {

  linearLayout = getViewById(R.id.linearLayout) 
}
Before
private lateinit var linearLayout: LinearLayout override fun onCreate(savedInstanceState: Bundle) {
 linearLayout = findViewById(R.id.linearLayout) as LinearLayout 
}

Padding

override fun onCreate(savedInstanceState: Bundle) {

  ...
  firstView.setOptionalPadding(bottom = 16)
  secondView.setAllPadding(16)
  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  firstView.setPadding(firstView.paddingLeft, firstView.paddingTop, firstView.paddingRight, 16)
  secondView.setPadding(16, 16, 16, 16)
  ... 
}

Post runnables

override fun onCreate(savedInstanceState: Bundle) {

  ...
  refreshLayout.postDelayedApply(3000) {

isRefreshing = false

clearAnimation()
  
}

  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  refreshLayout.postDelayed({

refreshLayout.isRefreshing = false

refreshLayout.clearAnimation()
  
}
, 3000)
  ... 
}

Also see postApply, postLet, postDelayedLet

Shared preferences

Delegates

class AccountRepository : SharedPreferencesProvider {

 override val sharedPreferences: SharedPreferences

 var currentUserId by PreferencesDelegates.int()

  constructor(context: Context) {

this.sharedPreferences = context.defaultSharedPreferences
  
}
 
}
Before
class AccountRepository {
 val sharedPreferences: SharedPreferences  constructor(context: Context) {

  this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) 
}
  var currentUserId: Int = 0
  get() = sharedPreferences.getInt(CURRENT_USER_ID, 0)
  set(value) {

sharedPreferences.edit().putInt(CURRENT_USER_ID, value).apply()

field = value
  
}

companion object {

const val CURRENT_USER_ID = "CURRENT_USER_ID" 
}
  
}

Shortcuts

sharedPreferences.save(CURRENT_USER_ID, userId)

 ...

sharedPreferences.save(BEARER_TOKEN, token, force = true)
Before
sharedPreferences.edit()
  .putInt(CURRENT_USER_ID, userId)
  .apply() ... sharedPreferences.edit() .putString(BEARER_TOKEN, token) .commit()

Context

Compat

override fun onCreate(savedInstanceState: Bundle) {

  ...
  val color = getThemedColor(R.color.cyan)
  val drawable = getThemedDrawable(R.drawable.background)
  val stateList = getThemedColorStateList(R.drawable.state_list)
  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  val color = ContextCompat.getColor(this, R.color.cyan)
  val drawable = ContextCompat.getDrawable(this, R.drawable.background)
  val stateList = ContextCompat.getColorStateList(this, R.drawable.state_list)
  ... 
}

Services

override fun onCreate(savedInstanceState: Bundle) {

  ...
  val inflater = layoutInflater
  val sharedPreferences = defaultSharedPreferences
  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
  val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
  ... 
}

Toasts

override fun onCreate(savedInstanceState: Bundle) {

  ...
  showShortToast("Hi!")
  showLongToast(R.string.hello)
  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  Toast.makeText(this, "Hi!", Toast.LENGTH_SHORT).show()
  Toast.makeText(this, R.string.hello, Toast.LENGTH_LONG).show()
  ... 
}

Permissions

override fun onCreate(savedInstanceState: Bundle) {

  ...
  if (isPermissionsGranted(Permission.WRITE_EXTERNAL_STORAGE, Permission.ACCESS_FINE_LOCATION)) {

...

 
}

  ... 
}
Before
override fun onCreate(savedInstanceState: Bundle) {

  ...
  if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&

 ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

  ...

}
 ...  
}

SQLiteDatabase

Queries

val db: SQLiteDatabase
override fun getAllUsers() {

  ...
  val cursor = db.executeQuery(table = TABLE_USERS, orderBy = COLUMN_NAME)
  ...
  db.executeDelete(table = TABLE_USERS)
  ... 
}
Before
val db: SQLiteDatabase override fun getAllUsers() {
 ... val cursor = db.query(TABLE_USERS, null, null, null, null, null, COLUMN_NAME) ... db.delete(TABLE_USERS, null, null) ... 
}

Also see executeInsert, executeUpdate.

Use with SQLiteDatabase and Cursor

fun runQuery(helper: SQLiteOpenHelper) = helper.writableDatabase.use {
 db ->
  db.query( ... ).use {
 cursor ->

 
}
 
}
Before
fun runQuery(helper: SQLiteOpenHelper) {

  val db = helper.writableDatabase
  val cursor = db.query( ... )
  ...
  cursor.close()
  db.close() 
}

Important: you should use extension method, not from kotlin-stlib because you can get ClassCastException. See this link.

License

Copyright (C) 2017 Artem Glugovsky  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

Twitter like toolbar indicator for Android.

A custom view to enter a four digit code usually in cases of authentication.

A Simple and Colorful alternative to showing Toasts.

One custom view for show something just like cards with animations.

An implementation of spring-like header (known as pull-to-refresh) that using CoordinatorLayout.

Android image group view - it can can show and add images.

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