Metuuu
1/12/2018 - 4:57 PM

Android Helper Functions

Useful functions to help workflow.


import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.location.LocationManager
import android.support.v7.app.AlertDialog
import android.text.Editable
import android.view.inputmethod.InputMethodManager
import android.util.DisplayMetrics
import android.util.Patterns
import android.view.*
import android.widget.Toast
import com.bromeco.tolppa.R
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_change_email.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern


/**
 * Created by lauri on 03/01/2018.
 */
object Helper {

	fun dpToPx(dp: Int): Int {
		return (dp * Resources.getSystem().displayMetrics.density).toInt()
	}

	fun pxToDp(px: Int): Int {
		return (px / Resources.getSystem().displayMetrics.density).toInt()
	}

	/*fun setTextAppearance(textView: TextView, c: Context, resId: Int): TextView {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
			textView.setTextAppearance(c, resId)
		} else {
			textView.setTextAppearance(resId)
		}
		return textView
	}*/


	/*  SOFT KEYBOARD  */
	fun hideSoftKeyboard(window: Window?) {
		val inputManager = window?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
		inputManager.hideSoftInputFromWindow(window.decorView?.rootView?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
	}
	fun showSoftKeyboard(c: Context?) {
		val inputManager = c?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
		inputManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS)
	}


	/*  SCREEN SIZE  */
	fun getScreenHeight(windowManager: WindowManager): Int {
		val displayMetrics = DisplayMetrics()
		windowManager.defaultDisplay.getMetrics(displayMetrics)
		return displayMetrics.heightPixels
	}
	fun getScreenWidth(windowManager: WindowManager): Int {
		val displayMetrics = DisplayMetrics()
		windowManager.defaultDisplay.getMetrics(displayMetrics)
		return displayMetrics.widthPixels
	}


	/* IS TABLET */
	fun isTablet(c: Context): Boolean {
		return c.resources.configuration.screenLayout and Configuration.SCREENLAYOUT_SIZE_MASK >= Configuration.SCREENLAYOUT_SIZE_LARGE
	}


	/*  NAVIGATION BAR HEIGHT  */
	fun getNavBarHeight(c: Context): Int {
		val result = 0
		val hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey()
		val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)

		if (!hasMenuKey && !hasBackKey) {
			//The device has a navigation bar
			val resources = c.resources

			val orientation = resources.configuration.orientation
			val resourceId: Int
			resourceId = if (isTablet(c)) resources.getIdentifier(if (orientation == Configuration.ORIENTATION_PORTRAIT) "navigation_bar_height" else "navigation_bar_height_landscape", "dimen", "android")
			else resources.getIdentifier(if (orientation == Configuration.ORIENTATION_PORTRAIT) "navigation_bar_height" else "navigation_bar_width", "dimen", "android")

			if (resourceId > 0) return resources.getDimensionPixelSize(resourceId)
		}
		return result
	}


	/*  STATUS BAR HEIGHT  */
	fun getStatusBarHeight(c: Context): Int {
		var result = 0
		val resourceId = c.resources.getIdentifier("status_bar_height", "dimen", "android")
		if (resourceId > 0) {
			result = c.resources.getDimensionPixelSize(resourceId)
		}
		return result
	}


	/*  CONNECTIVITY  */
	fun isGpsOnWithDialogAlert(locationManager: LocationManager, context: Context): Boolean {
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			val alertDialog = AlertDialog.Builder(context).create()
			alertDialog.setMessage(context.resources.getString(R.string.warn_enable_gps))
			alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, context.resources.getString(R.string.ok), { dialog, _ -> dialog.dismiss() })
			alertDialog.show()
			return false
		}
		return true
	}
	fun isGpsOnToastAlert(locationManager: LocationManager, context: Context): Boolean {
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(context, context.resources.getString(R.string.warn_gps_not_enabled), Toast.LENGTH_SHORT).show()
			return false
		}
		return true
	}
	fun isGpsOn(locationManager: LocationManager): Boolean {
		return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
	}

	/* DATE FUNCTIONS */
	fun millisecondsToDate(milliseconds: Long, context: Context): String {
		val formatter = SimpleDateFormat("dd.mm.yyyy")
		return formatter.format(Date(milliseconds))
	}
	

	/* VALIDATION */
	fun validEmail(editable: Editable): Boolean {
		return Patterns.EMAIL_ADDRESS.matcher(editable.toString()).matches()
	}

	/* TYPE TOKEN */
	inline fun <reified T> typeToken(): TypeToken<T> {
		return object: TypeToken<T>() {}
	}

}