Exposed drop-down menu for jetpack compose

The M2 (starting from the version 1.1.0-alpha06) and M3 have the implementation of ExposedDropdownMenu based on ExposedDropdownMenuBox with TextField and DropdownMenu inside. Something like: val options = listOf(“Option 1”, “Option 2”, “Option 3”, “Option 4”, “Option 5”) var expanded by remember { mutableStateOf(false) } var selectedOptionText by remember { mutableStateOf(options[0]) } ExposedDropdownMenuBox( expanded = expanded, … Read more

Kotlin Ternary Conditional Operator

In Kotlin, if statements are expressions. So the following code is equivalent: if (a) b else c The distinction between expression and statement is important here. In Java/C#/JavaScript, if forms a statement, meaning that it does not resolve to a value. More concretely, you can’t assign it to a variable. // Valid Kotlin, but invalid … Read more

How to pass id and application to a viewModel/viewModelFactory in Jetpack Compose?

To answer your question: you retrieve the Application from the LocalContext object: val context = LocalContext.current val application = context.applicationContext as Application However, when using Navigation Compose, you don’t need to manually pass any arguments to your ViewModel. Instead, you can utilize the built in support for SavedState in ViewModels and add a SavedStateHandle parameter … Read more

FragmentTransaction hide/show doesn’t work sometimes

You need to reuse the same instance of a fragment that you wanted to hide or show. private fun replaceFragment(fragment: Fragment) { supportFragmentManager.beginTransaction().apply { if (fragment.isAdded) { show(fragment) } else { add(R.id.fmFragmentContainer, fragment) } supportFragmentManager.fragments.forEach { if (it != fragment && it.isAdded) { hide(it) } } }.commit() }

fillMaxSize modifier not working when combined with VerticalScroll in Jetpack Compose

verticalScroll wraps the height of the content, and can be stretched to very long, so the scope has Constraints.Infinity for maxHeight constraint. From fillMaxHeight documentation If the incoming maximum height is Constraints.Infinity this modifier will have no effect. That’s why you need to set height explicitly. Consider switching to LazyColumn(which has fillParentMaxHeight() for this exact … Read more

How can I debounce a setOnClickListener for 1 second using Kotlin Coroutines?

Couroutines are overkill for something as trivial as debounce: class DebounceOnClickListener( private val interval: Long, private val listenerBlock: (View) -> Unit ): View.OnClickListener { private var lastClickTime = 0L override fun onClick(v: View) { val time = System.currentTimeMillis() if (time – lastClickTime >= interval) { lastClickTime = time listenerBlock(v) } } } fun View.setOnClickListener(debounceInterval: Long, … Read more