Some Helper Functions For Extension Development - Kotlin

These are some helper functions that may help you in extension development. Written in Kotlin.


import com.google.appinventor.components.runtime.Form
import com.google.appinventor.components.runtime.ReplForm
import java.io.FileInputStream
import java.io.InputStream
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.Log
import android.util.TypedValue

const val LOG_TAG = "HelperFunctions"

fun getDrawable(form: Form, fileName: String): Drawable? {
    return try {
        val inputStream: InputStream? = getAsset(form, fileName)
        val drawable: Drawable = Drawable.createFromStream(inputStream, null)
        inputStream?.close()
        drawable
    } catch (e: Exception) {
        Log.v(LOG_TAG, "getDrawable : Error = $e")
        null
    }
}

fun getAsset(form: Form, file: String): InputStream? {
    val context = form.`$context`()
    val isDebugMode = form is ReplForm
    return try {
        if (isDebugMode) {
            val path: String = getAssetPath(context, file)
            Log.v(LOG_TAG, "getAsset | Filepath = $path")
            FileInputStream(path)
        } else {
            context.assets.open(file)
        }
    } catch (e: Exception) {
        Log.e(LOG_TAG, "getAsset | Debug Mode : $isDebugMode | Error : $e")
        null
    }
}

fun getTypeface(form: Form, asset: String): Typeface {
    val context = form.`$context`()
    val isDebugMode = form is ReplForm
    return try {
        if (isDebugMode) {
            val path = getAssetPath(context, asset)
            Typeface.createFromFile(path)
        } else {
            val path = form.getAssetPath(asset)
            Typeface.createFromFile(path)
        }
    } catch (e: Exception) {
        Log.e(LOG_TAG, "getTypeface | Failed to get typeface from path : $asset with error : $e")
        Typeface.DEFAULT;
    }
}

private fun getAssetPath(context: Context, file: String) = when {
    context.javaClass.name.contains("makeroid") -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            context.getExternalFilesDir(null).toString() + "/assets/$file"
        } else {
            "/storage/emulated/0/Kodular/assets/$file"
        }
    }
    else -> context.getExternalFilesDir(null).toString() + "/AppInventor/assets/$file"
}

/** Convert dp to px */
fun Int.px(): Int {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this.toFloat(),
        android.content.res.Resources.getSystem().displayMetrics
    ).toInt()
}

/** Convert sp to px */
fun Int.sp(): Int {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP,
        this.toFloat(),
        android.content.res.Resources.getSystem().displayMetrics
    ).toInt()
}

10 Likes