Snippets Collections
val painter = rememberImagePainter(
    data = url,
    builder = {
        crossfade(true) //Crossfade animation between images
        placeholder(R.drawable.ic_image_loading) //Used while loading
        fallback(R.drawable.ic_empty) //Used if data is null
        error(R.drawable.ic_empty) //Used when loading returns with error
    }
)
Row(
    modifier = Modifier.padding(16.dp),
    horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
    //Important image loading part
    //Remembering of painter
    val painter = rememberImagePainter(data = cat.photoUrl)
	
    Image(
       modifier = Modifier
           .size(100.dp)
           .clip(RoundedCornerShape(16.dp)),
       //Use painter in Image composable
       painter = painter,
       contentDescription = "Cat"
    )
    //Rest of compose code
}
Image(
    painter = ColorPainter(Color.Yellow), 
    contentDescription = "Yellow rectangle"
)
Image(
    imageVector = Icons.Default.Info,
    contentDescription = "Cat informations"
)
val bitmap = getBitmapFromYourSource()
Image(
    bitmap = bitmap, 
    contentDescription = "Cat"
)
@Composable
fun Image(
    //bitmap or vector or painter
    contentDescription: String?,
    modifier: Modifier = Modifier,
    alignment: Alignment = Alignment.Center,
    contentScale: ContentScale = ContentScale.Fit,
    alpha: Float = DefaultAlpha,
    colorFilter: ColorFilter? = null
)
SnackbarHost(
    modifier = Modifier.align(Alignment.BottomCenter),
    hostState = snackbarHostState,
    snackbar = { snackbarData: SnackbarData ->
        Card(
            shape = RoundedCornerShape(8.dp),
            border = BorderStroke(2.dp, Color.White),
            modifier = Modifier
                .padding(16.dp)
                .wrapContentSize()
        ) {
            Column(
                modifier = Modifier.padding(8.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Icon(imageVector = Icons.Default.Notifications, contentDescription = "")
                Text(text = snackbarData.message)
            }
        }
    }
)
@Composable
fun SnackbarScreen() {
    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }
    .
    .
    .
    FloatingActionButton(
        onClick = {
	    //Important part here
            scope.launch {
                snackbarHostState.showSnackbar("Hello there")
            }
	    //
        },
        content = { Icon(imageVector = Icons.Default.Add, contentDescription = "") }
    )
	
    SnackbarHost(hostState = snackbarHostState)
}
val snackbarHostState = remember { SnackbarHostState() }
.
.
.
SnackbarHost(hostState = snackbarHostState)
@Composable
fun SnackbarHost(
    hostState: SnackbarHostState,
    modifier: Modifier = Modifier,
    snackbar: @Composable (SnackbarData) -> Unit = { Snackbar(it) }
)
content: @Composable (PaddingValues) -> Unit
val scope = rememberCoroutineScope()
val scaffoldState = rememberScaffoldState()
.
.
.
scaffoldState = scaffoldState,
floatingActionButton = {
    FloatingActionButton(
        onClick = {
            scope.launch {
                scaffoldState.snackbarHostState.showSnackbar("Hello there!")
            }
        },
        content = {
            Icon(imageVector = Icons.Default.Favorite, contentDescription = "")
        }
    )
}
snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) }
drawerContent = {
    Icon(
        modifier = Modifier.padding(16.dp),
        imageVector = Icons.Default.Person,
        contentDescription = ""
    )
    Text(modifier = Modifier.padding(16.dp), text = "First line")
    Text(modifier = Modifier.padding(16.dp), text = "Second line")
    Text(modifier = Modifier.padding(16.dp), text = "Third line")
}
drawerContent: @Composable (ColumnScope.() -> Unit)? = null
floatingActionButton = {
    FloatingActionButton(
        onClick = {},
        content = {
            Icon(imageVector = Icons.Default.Favorite,contentDescription = "")
        }
    )
}
floatingActionButton: @Composable () -> Unit = {}
bottomBar = {
    BottomAppBar(
        content = {
            Icon(modifier = padding, imageVector = Icons.Default.Menu, contentDescription = "Menu")
            Icon(modifier = padding, imageVector = Icons.Default.Search, contentDescription = "Search")
            Text(text = "Anything can be here")
        }
    )
}
bottomBar: @Composable () -> Unit = {}
topBar = {
    TopAppBar(
        title = { Text(text = "Title text") },
        navigationIcon = {
            Icon(modifier = padding, imageVector = Icons.Default.ArrowBack, contentDescription = "Back")
        },
        actions = {
            Icon(modifier = padding, imageVector = Icons.Default.Favorite, contentDescription = "Favorite")
            Icon(modifier = padding, imageVector = Icons.Default.Search, contentDescription = "Search")
        }
    )
}
topBar: @Composable () -> Unit = {}
@Composable
fun Scaffold(
    modifier: Modifier = Modifier,
    scaffoldState: ScaffoldState = rememberScaffoldState(),
    topBar: @Composable () -> Unit = {},
    bottomBar: @Composable () -> Unit = {},
    snackbarHost: @Composable (SnackbarHostState) -> Unit = { SnackbarHost(it) },
    floatingActionButton: @Composable () -> Unit = {},
    floatingActionButtonPosition: FabPosition = FabPosition.End,
    isFloatingActionButtonDocked: Boolean = false,
    drawerContent: @Composable (ColumnScope.() -> Unit)? = null,
    drawerGesturesEnabled: Boolean = true,
    drawerShape: Shape = MaterialTheme.shapes.large,
    drawerElevation: Dp = DrawerDefaults.Elevation,
    drawerBackgroundColor: Color = MaterialTheme.colors.surface,
    drawerContentColor: Color = contentColorFor(drawerBackgroundColor),
    drawerScrimColor: Color = DrawerDefaults.scrimColor,
    backgroundColor: Color = MaterialTheme.colors.background,
    contentColor: Color = contentColorFor(backgroundColor),
    content: @Composable (PaddingValues) -> Unit
)
date    .text = string(R.string.attendance_detail_header_date)
category.text = string(R.string.attendance_detail_header_category)
time    .text = string(R.string.attendance_detail_header_time)
duration.text = string(R.string.attendance_detail_header_duration)
shift   .text = string(R.string.attendance_detail_header_time)
arrival .text = string(R.string.attendance_detail_header_arrival)
date.text = string(R.string.attendance_detail_header_date)
category.text = string(R.string.attendance_detail_header_category)
time.text = string(R.string.attendance_detail_header_time)
duration.text = string(R.string.attendance_detail_header_duration)
shift.text = string(R.string.attendance_detail_header_time)
arrival.text = string(R.string.attendance_detail_header_arrival)
fun View.actionsPage(
    actions: List<Action>,
    grid: Grid,
    itemsPerPage: Int,
    position: Int,
    settings: Settings
) = whenAttached { }


fun View.actionsPage(
    actions      : List<Action>,
    grid         : Grid,
    itemsPerPage : Int,
    position     : Int,
    settings     : Settings
) = whenAttached { }
data class EmployeeDetail(
    val employee: Employee,
    val personalNumber: PersonalNumber,
    val hasCard: Boolean,
    val hasPin: Boolean,
    val fingerprints: List<Finger>
)


data class EmployeeDetail(
    val employee       : Employee,
    val personalNumber : PersonalNumber,
    val hasCard        : Boolean,
    val hasPin         : Boolean,
    val fingerprints   : List<Finger>
)
class FunctionProcessorProvider : SymbolProcessorProvider {

    override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
        return FunctionProcessor(
            options = environment.options,
            logger = environment.logger,
            codeGenerator = environment.codeGenerator
        )
    }
}
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
enum class PaymentOption {
    CASH,
    CARD,
    TRANSFER
}

fun PaymentOption.startPayment(transaction: TransactionData) {
    when (this) {
        PaymentOption.CASH -> showCashPaimentInfo(transaction)
        PaymentOption.CARD -> moveToCardPaymentPage(transaction)
        PaymentOption.TRANSFER -> {
            showMoneyTransferInfo()
            setupPaymentWatcher(transaction)
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>

  <ScrollView

        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:fillViewport="true"
  >

    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/constraint_layout1"
            >


        <com.google.android.material.textfield.TextInputLayout

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toTopOf="@+id/username_input_layout"
                android:padding="16dp"
                app:helperText="Email"
                android:id="@+id/email_input_layout"
                app:layout_constraintVertical_chainStyle="packed"
                app:layout_constraintVertical_bias=".1"

        >

            <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/email"
                    android:textColor="#000"
                    android:hint="@string/your_email"
                    android:textSize="20sp"
            />

        </com.google.android.material.textfield.TextInputLayout>


        <com.google.android.material.textfield.TextInputLayout

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/email_input_layout"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toTopOf="@+id/change_password"
                android:padding="16dp"
                app:helperText="Username"
                android:id="@+id/username_input_layout"

        >

            <TextView

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/username"
                    android:textColor="#000"
                    android:hint="@string/your_username"
                    android:textSize="20sp"

            />

        </com.google.android.material.textfield.TextInputLayout>


        <TextView

                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/username_input_layout"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:textSize="18sp"
                android:textColor="@color/link_blue"
                android:text="@string/change_password"
                android:id="@+id/change_password"
                android:gravity="center"

        />

        <Button

                android:id="@+id/logout_button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/change_password"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                android:background="@drawable/red_button_drawable"
                android:text="Log out"
                android:textAllCaps="false"
                android:textColor="#fff"
                android:textSize="16sp"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_marginTop="50dp"
                android:layout_marginBottom="30dp"

        />
                  
    </androidx.constraintlayout.widget.ConstraintLayout>


</ScrollView>
// Create an array and instantiate a listview
val myArray : MutableList<BigInteger> = mutableListOf(); val lstView = findViewById<ListView>(R.id.lsvw)

// Create an adapter and link it to the listview
val arrayAdapter : ArrayAdapter<BigInteger> = ArrayAdapter<BigInteger(this, android.R.layout.simple_list_item_1, myArray)
lstView.adapter = arrayAdapter

// Add data to the array and push it to the adapter
myArray.add(<data>)
arrayAdapter.notifyDataSetChanged()
userInput.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->

	if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {

		//code
		return@OnKeyListener true

	}

	false

})
var a = 1;
var b = 2;
    
a = b.also { b = a } // now a = 2, b = 1
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.Group
	android:id="@+id/group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:constraint_referenced_ids="text,button"/>

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Text"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.google.android.material.button.MaterialButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"
        app:layout_constraintTop_toBottomOf="@id/text"/>
    
</androidx.constraintlayout.widget.ConstraintLayout>
class SleepTrackerViewModelFactory(
       private val dataSource: SleepDatabaseDao,
       private val application: Application) : ViewModelProvider.Factory {
   @Suppress("unchecked_cast")
   override fun <T : ViewModel?> create(modelClass: Class<T>): T {
       if (modelClass.isAssignableFrom(SleepTrackerViewModel::class.java)) {
           return SleepTrackerViewModel(dataSource, application) as T
       }
       throw IllegalArgumentException("Unknown ViewModel class")
   }
}
// MyFragment.kt

class MyFragment : Fragment(R.layout.fragment_my) {
  
  private var _binding: MyFragmentBinding? = null
  private val binding get() = _binding!!

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    _binding = MyFragmentBinding.bind(view)
    
    binding.someview.text = "bla bla"
  }

  override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
  }
}
@RequestMapping(produces = [MediaType.TEXT_HTML_VALUE, CustomMediaType.TURBO_STREAM_VALUE])
suspend fun pinger(model: Model): String {
    model.addAttribute("pingTime", pingService.ping(hostname, port))
    return "ping.turbo-stream"
}
listOf(0,1,2,null,4,null,6,7).forEach{
     it?.let{
         println(it)
     } ?: println("null detected")
 }
package adapter

import android.content.Context
import android.view.ViewGroup
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import domain.ViewType
import domain.movie.ListaItemFilme
import pessoaspopulares.adapter.LoadingDelegateAdapter
import pessoaspopulares.adapter.ViewTypeDelegateAdapter
import utils.Constant

/**
 * Created by icaro on 14/08/16.
 */
class ListUserAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val listaResult = ArrayList<ViewType>()
    private val delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()

    init {
        delegateAdapters.put(Constant.ViewTypesIds.LOADING, LoadingDelegateAdapter())
        delegateAdapters.put(Constant.ViewTypesIds.NEWS, ListasDelegateAdapter())
        listaResult.add(loading)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, listaResult[position], context)
    }

    override fun getItemViewType(position: Int): Int {
        return listaResult[position].getViewType()
    }

    fun addItens(listaMedia: List<ListaItemFilme?>?, totalResults: Int) {
        if (listaMedia?.isNotEmpty()!!) {
            val initPosition = listaResult.size - 1
            this.listaResult.removeAt(initPosition)
            notifyItemRemoved(initPosition)
            for (result in listaMedia) {
                this.listaResult.add(result!!)
            }
            this.listaResult.sortedBy { (it as ListaItemFilme).releaseDate }
                .reversed()
            notifyItemRangeChanged(initPosition, this.listaResult.size + 1 /* plus loading item */)
            if (listaResult.size < totalResults)
                this.listaResult.add(loading)
        }
    }

    override fun getItemCount(): Int = listaResult.size

    companion object {

        private val loading = object : ViewType {
            override fun getViewType(): Int {
                return Constant.ViewTypesIds.LOADING
            }
        }
    }
}





@Keep
interface ViewType {
    fun getViewType(): Int
}

interface ViewTypeDelegateAdapter {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder

    fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?)
}



class LoadingDelegateAdapter : ViewTypeDelegateAdapter {

    override fun onCreateViewHolder(parent: ViewGroup) = LoadingViewHolder(parent)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?) {
    }

    class LoadingViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.new_item_loading, parent, false))
}


class ListasDelegateAdapter : ViewTypeDelegateAdapter {

	override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
		ListViewHolder(parent)

	override fun onBindViewHolder(
		holder: RecyclerView.ViewHolder,
		item: ViewType?,
		context: Context?
	) {
		(holder as ListViewHolder).bind(item as ListaItemFilme)
	}

	inner class ListViewHolder(parent: ViewGroup) :
		RecyclerView.ViewHolder(
			LayoutInflater.from(parent.context).inflate(R.layout.lista, parent, false)
		) {

		fun bind(item: ListaItemFilme) = with(itemView) {

			img_lista.setPicassoWithCache(item.posterPath, 3)
			when (item.mediaType) {
				"tv" -> date_oscar.text =
					if (!item.first_air_date.isNullOrEmpty() && item.first_air_date.length > 3)
						item.first_air_date.subSequence(0, 4) else "-"
				"movie" -> date_oscar.text =
					if (!item.releaseDate.isNullOrEmpty() && item.releaseDate.length > 3)
						item.releaseDate.subSequence(0, 4) else "-"
			}

			progress.visibility = View.GONE
			itemView.setOnClickListener {
				when (item.mediaType) {
					"tv" -> {
						val intent = Intent(context, TvShowActivity::class.java).apply {
							putExtra(Constant.TVSHOW_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
					"movie" -> {
						val intent = Intent(context, MovieDetailsActivity::class.java).apply {
							putExtra(Constant.FILME_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
				}
			}
		}
	}
}

  
package utils

import android.animation.Animator
import android.animation.Animator.*
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.util.Log
import android.view.View
import android.view.ViewGroup.*
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.marginTop
import androidx.fragment.app.FragmentActivity
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import applicaton.BaseViewModel.*
import applicaton.BaseViewModel.BaseRequest.*
import br.com.icaro.filme.R
import com.github.clans.fab.FloatingActionMenu
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.gson.Gson
import com.squareup.picasso.Callback
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import domain.reelgood.movie.Availability
import domain.tvshow.Tvshow
import error.BottomSheetError
import error.CallBackError
import java.text.DateFormat
import java.text.Normalizer
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Created by icaro on 03/09/17.
 */
/**
 * IMAGEVIEW
 */
fun ImageView.setPicasso(
	stillPath: String?,
	patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE)
		.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCache(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCacheAndHolder(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
	holder: Int,
): ImageView {
	Picasso.get()
		.load(UtilsApp.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath)
		.placeholder(holder)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.loadPallet(): Int? {
	val color = (drawable as? BitmapDrawable)?.run {
		Palette.Builder(this.bitmap).generate().swatches.first().rgb
	}
	return color ?: 0
}

fun loadPalette(view: ImageView): Int { // Todo Usar ext
	val imageView = view as ImageView
	val drawable = imageView.drawable as? BitmapDrawable
	if (drawable != null) {
		return Palette.Builder(drawable.bitmap).generate().swatches.last().rgb
	}
	return 0
}

/**
 * ACTIVITY
 */
fun Activity.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Activity.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * Context
 */
fun Context.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * VIEW
 */
fun View.gone() {
	this.visibility = View.GONE
}

fun View.visible() {
	this.visibility = View.VISIBLE
}

fun View.invisible() {
	this.visibility = View.INVISIBLE
}

fun View.animeRotation(
	end: () -> Unit = {},
	cancel: () -> Unit = {},
	start: () -> Unit = {},
	repeat: () -> Unit = {},
) {
	ObjectAnimator
		.ofPropertyValuesHolder(
			this,
			PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f)
		)
		.apply {
			duration = 790
			addListener(object : AnimatorListener {
				override fun onAnimationRepeat(animation: Animator?) {
					repeat()
				}

				override fun onAnimationEnd(animation: Animator?) {
					end()
				}

				override fun onAnimationCancel(animation: Animator?) {
					cancel()
				}

				override fun onAnimationStart(animation: Animator?) {
					start()
				}
			})
		}.start()
}

/**
 * Any
 */
fun Any.putString(cxt: Context): String = when (this) {
	is String -> this
	is Int -> cxt.getString(this)
	else -> {
		require(false) { "Need R.string.id or string" }
		""
	}
}

/**
 * STRING
 */
fun String.removerAcentos(): String {
	this.replace(".", "")
	this.replace(":", "")
	this.replace("/", "")
	this.replace(";", "")
	return Normalizer.normalize(this, Normalizer.Form.NFD).replace("[^\\p{ASCII}]".toRegex(), "")
}

fun String.parseDate(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun String.parseDateShot(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun verifyLaunch(air_date: Date?): Boolean {
	if (air_date == null) return false
	val now = Calendar.getInstance().time
	return if (air_date.before(now)) {
		true
	} else !air_date.after(now)
}

fun String.getDate(format: String = "yyyy-MM-dd"): Date? {
	return try {
		let {
			val sdf = SimpleDateFormat(format, Locale.getDefault())
			sdf.parse(it)
		}
	} catch (e: ParseException) {
		e.printStackTrace()
		null
	}
}

fun String.released(): Boolean {
	val data = getDate()
	return verifyLaunch(data)
}

@Throws(Exception::class)
fun String.yearDate(): String {
	return if (this.length >= 4) this.substring(0, 4) else ""
}

fun String.periodLaunch(): Boolean {
	val oneWeekBack = Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -7) }.time
	return getDate() != null && getDate()!!.after(oneWeekBack) //valida data
}

fun String.getNameTypeReel(): String {
	return replace(":", "-")
		.replace(" ", "-")
		.replace("&", "and")
		.replace(".", "")
		.replace("é", "e")
		.replace("ẽ", "e")
		.replace("è", "e")
		.replace("ë", "e")
		.replace("ç", "c")
		.replace("â", "a")
		.replace("ã", "a")
		.replace("á", "a")
		.replace("à", "a")
		.replace("ä", "a")
		.replace("ä", "a")
		.replace("'", "")
		.replace("\"", "")
		.replace("´", "")
		.replace("~", "")
		.replace("^", "")
		.replace("---", "-")
		.replace("----", "-")
		.replace("--", "-")
		.toLowerCase()
}

fun String?.notNullOrEmpty() = !this.isNullOrEmpty()
fun <T> Gson.fromJsonWithLog(json: String?, classOfT: Class<T>): T {
	return this.fromJson<T>(json, classOfT).apply {
		this.toString().log(classOfT.name)
	}
}

fun String.log(tag: String = "") = Log.i(tag, this)

fun Tvshow.createIdReal() = createIdReal(this.originalName ?: "", this.firstAirDate ?: "")
private fun createIdReal(originalName: String, data: String) =
	"${originalName.getNameTypeReel()}-${data.yearDate()}"

/**
 * RECYCLER
 */
fun RecyclerView.setScrollInvisibleFloatMenu(floatButton: FloatingActionMenu) {
	addOnScrollListener(object : RecyclerView.OnScrollListener() {
		override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
			when (newState) {
				RecyclerView.SCROLL_STATE_IDLE -> floatButton.visible()
				RecyclerView.SCROLL_STATE_DRAGGING -> floatButton.invisible()
				RecyclerView.SCROLL_STATE_SETTLING -> floatButton.invisible()
			}
		}
	})
}

@SuppressLint("WrongConstant")
fun RecyclerView.patternRecyler(horizont: Boolean = true): RecyclerView {
	val typeOrient = if (horizont) LinearLayoutManager.HORIZONTAL else LinearLayoutManager.VERTICAL
	layoutManager = LinearLayoutManager(context, typeOrient, false)
	itemAnimator = DefaultItemAnimator()
	setHasFixedSize(true)
	return this
}

fun RecyclerView.patternRecyclerGrid(quant: Int = 2): RecyclerView {
	layoutManager = GridLayoutManager(context, quant)
	setHasFixedSize(true)
	itemAnimator = DefaultItemAnimator()
	return this
}

fun RecyclerView.minHeight(): RecyclerView {
	layoutParams.height = 1
	importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
	isFocusable = false
	return this
}

/**
 * AVAILABILITY
 */
fun Availability.getPricePurchase(): String {
	val less = purchaseCostSd?.let { purchaseCostHd?.coerceAtMost(it) }
	val biggest = purchaseCostSd?.let { purchaseCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

fun Availability.getPriceRental(): String {
	val less = rentalCostSd?.let { rentalCostHd?.coerceAtMost(it) }
	val biggest = rentalCostSd?.let { rentalCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

/**
 * BottomSheetBehavior
 */
fun BottomSheetBehavior<View>.setAnimation(container: View, viewHeight: View) {
	ValueAnimator.ofInt(container.measuredHeight, viewHeight.marginTop).apply {
		addUpdateListener {
			peekHeight = it.animatedValue as Int
		}
		duration = 500
	}.start()

	container.post {
		val newLayoutParams = (container.layoutParams as? MarginLayoutParams)
		newLayoutParams?.setMargins(0, 0, 0, viewHeight.marginTop + 1)
		container.layoutParams = newLayoutParams
	}
}

/**
 * MutableList
 */
fun <T> MutableList<T>.replaceItemList(item: T, predicate: (T) -> Boolean): MutableList<T> {
	return this.map {
		if (predicate(it)) item else it
	}.toMutableList()
}

fun <T> Any.listSize(item: T, size: Int): ArrayList<T> {
	return if (size <= 0) {
		arrayListOf()
	} else {
		arrayListOf<T>().apply {
			for (i in 0 until size) {
				add(item)
			}
		}
	}
}

/**
 * BaseRequest
 */
fun <T> BaseRequest<T>.success() = (this as Success<T>).result
fun <T> BaseRequest<T>.resolver(
	activity: FragmentActivity,
	successBlock: (data: T) -> Unit,
	failureBlock: (error: Exception) -> Unit = {},
	loadingBlock: (loading: Boolean) -> Unit = {},
	genericError: CallBackError? = null,
) {
	when (this) {
		is Success -> successBlock(result)
		is Loading -> loadingBlock(loading)
		is Failure -> {
			error.toString().log()
			if (genericError != null) {
				BottomSheetError().newInstance(callBackError = genericError)
					.show(activity.supportFragmentManager, "")
			} else {
				failureBlock(error)
			}
		}
	}
}


star

Mon Oct 04 2021 10:36:56 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:45:08 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:44:24 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:43:36 GMT+0000 (UTC)

#kotlin
star

Mon Oct 04 2021 05:41:58 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:32:42 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:32:08 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:31:33 GMT+0000 (UTC)

#kotlin
star

Mon Sep 20 2021 09:31:04 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:37:45 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:37:00 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:36:19 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:33:32 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:32:55 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:24:13 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:23:33 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:08:22 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 06:07:19 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:57:00 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:56:06 GMT+0000 (UTC)

#kotlin
star

Mon Sep 06 2021 05:55:17 GMT+0000 (UTC)

#kotlin
star

Mon Aug 16 2021 07:44:42 GMT+0000 (UTC)

#kotlin
star

Mon Jul 12 2021 18:39:02 GMT+0000 (UTC)

#kotlin
star

Mon Jun 21 2021 18:47:28 GMT+0000 (UTC) https://github.com/waliasanchit007/FirstJetpackCompose

#by #kotlin #jetpackcompose
star

Thu Jun 17 2021 13:30:51 GMT+0000 (UTC) https://blog.kotlin-academy.com/enum-vs-sealed-class-which-one-to-choose-dc92ce7a4df5

#kotlin #extensionfunction #enum
star

Tue May 11 2021 16:05:39 GMT+0000 (UTC)

#kotlin #android
star

Tue May 11 2021 16:02:40 GMT+0000 (UTC)

#kotlin #android
star

Tue May 11 2021 15:57:13 GMT+0000 (UTC)

#kotlin #android
star

Thu Apr 22 2021 13:25:56 GMT+0000 (UTC) https://medium.com/swlh/kotlin-tips-tricks-you-must-know-in-2021-172700af193a

#kotlin
star

Tue Mar 23 2021 07:48:35 GMT+0000 (UTC)

#kotlin
star

Fri Feb 26 2021 04:53:44 GMT+0000 (UTC) https://developer.android.com/codelabs/kotlin-android-training-coroutines-and-room

#kotlin #android
star

Wed Feb 03 2021 13:29:33 GMT+0000 (UTC)

#kotlin #android
star

Mon Jan 18 2021 05:24:39 GMT+0000 (UTC)

#kotlin #springframework
star

Wed Dec 16 2020 21:46:45 GMT+0000 (UTC) http://javaway.info/also-let-apply-with-run-shpargalka-po-funktsiyam-kotlin/

#kotlin
star

Sat Nov 21 2020 21:03:31 GMT+0000 (UTC)

#kotlin
star

Sat Nov 21 2020 20:59:49 GMT+0000 (UTC)

#kotlin

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension