Sobes.tech
Middle

Milliseid omadusi saate Androidis laiendusena lisada?

sobes.tech AI

Vastus AI-lt

In Android development, extension functions and properties allow adding new functionality to existing classes without inheritance or using decorators. This is especially useful when working with standard SDK classes.

Extension Properties are properties that we can add to existing classes. They do not store state; their computed value is determined by a getter.

Examples of using extension properties in Android:

  1. Simplifying access to LayoutInflater:

    // Adding an extension property for accessing LayoutInflater
    val Context.layoutInflater: LayoutInflater  
        get() = LayoutInflater.from(this)  
    

    Now you can use context.layoutInflater instead of LayoutInflater.from(context).

  2. Short property for hiding a View:

    // Extension property to set View visibility to GONE
    var View.isVisibleGone: Boolean  
        get() = visibility == View.VISIBLE // Getter for current state  
        set(value) { // Setter for setting state  
            visibility = if (value) View.VISIBLE else View.GONE  
        }
    

    Now you can use view.isVisibleGone = false to hide the View.

  3. Getting screen size in DP:

    // Extension property to get screen width in DP
    val Context.screenWidthInDp: Int  
        get() = resources.displayMetrics.widthPixels / resources.displayMetrics.density.toInt()  
    

    Example: context.screenWidthInDp.

  4. Access to SharedPreferences:

    // Extension function to get SharedPreferences by name
    fun Context.sharedPreferences(name: String): SharedPreferences =  
        getSharedPreferences(name, Context.MODE_PRIVATE)  
    

    Although this is a function, it is often used as a property for convenient access: context.sharedPreferences("my_prefs").

Important points about extension properties:

  • They cannot have backing fields.
  • They must be defined either with only a getter (read-only) or with a getter and setter (read-write).
  • They are compiled as static methods, so they are called through the owner class.

In general, in Android, you can add any computed property that logically belongs to an existing class and simplifies its usage, avoiding the creation of auxiliary functions or wrapper classes.