Kotlin extensions

At the end of this chapter, I would like to introduce you to the Kotlin extensions. No, not exactly the Kotlin extensions functions, although they are very much related to the Kotlin extension functions. Kotlin extensions is a curated list of the most commonly used extension functions in Android.

For example, if you want an extension function to create a bitmap from a View/ViewGroup instance (especially useful while adding Markers in MapFragment), you can copy and paste the following extension function from there:

    fun View.getBitmap(): Bitmap { 
      val bmp = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888) val canvas = Canvas(bmp) draw(canvas) canvas.save() return bmp }

Or, a more common case, when you need to hide your keyboard, the following extension function will help you:

    fun Activity.hideSoftKeyboard() { 
      if (currentFocus != null) { 
        val inputMethodManager = getSystemService(Context 
          .INPUT_METHOD_SERVICE) as InputMethodManager 
        inputMethodManager.hideSoftInputFromWindow
(currentFocus!!.windowToken, 0) } }

This online listing has a lot more extension functions for you, which are maintained by Ravindra Kumar (Twitter, GitHub—@ravidsrk). So, the next time you need an extension function, take a look at http://kotlinextensions.com/ before writing your own.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.221.144