Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dropdown improvements #65

Open
wants to merge 1 commit into
base: rostyslavAutoComplete
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.skyyo.samples.features.autoComplete

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.LayoutRes
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import com.google.android.material.textfield.TextInputLayout
import com.skyyo.samples.R

@Composable
fun AndroidViewDropdown(
modifier: Modifier = Modifier,
countries: List<String>,
selectedValue: String = "",
filter: (String) -> List<String>,
onSelect: (Int) -> Unit = {},
) {
val context = LocalContext.current
val textInputLayout = remember(countries) {
(View.inflate(context, R.layout.text_input_field, null) as TextInputLayout).also {
(it.editText as AutoCompleteTextView).apply {
val adapter = FilterableAdapter(countries, filter, context)
setOnItemClickListener { _, _, index, _ ->
onSelect(index)
}
setAdapter(adapter)
}
}
}

AndroidView(
modifier = modifier,
factory = { textInputLayout },
update = {
(textInputLayout.editText as AutoCompleteTextView).setText(selectedValue)
},
)
}

private class FilterableAdapter(
private val items: List<String>,
private val filterFun: (String) -> List<String>,
context: Context,
@LayoutRes private val layoutId: Int = android.R.layout.simple_list_item_1
) : BaseAdapter(), Filterable {

private val inflater = LayoutInflater.from(context)
private var allItems: List<String>? = null
private var filteredItems: List<String> = items
private val filterLock = Any()

private val adapterFilter: Filter = object : Filter() {
override fun performFiltering(prefix: CharSequence?): FilterResults {
if (allItems == null) {
synchronized(filterLock) { allItems = items }
}
val results: List<String>
if (prefix.isNullOrEmpty()) {
synchronized(filterLock) {
results = allItems!!
}
} else {
synchronized(filterLock) {
results = filterFun(prefix.toString())
}
}
return FilterResults().apply {
values = results
count = results.size
}
}

@Suppress("UNCHECKED_CAST")
override fun publishResults(constraint: CharSequence?, results: FilterResults) {
filteredItems = results.values as List<String>
if (results.count > 0) {
notifyDataSetChanged()
} else {
notifyDataSetInvalidated()
}
}
}

override fun getCount(): Int = filteredItems.size

override fun getItem(position: Int): Any = filteredItems[position]

override fun getItemId(position: Int): Long = position.toLong()

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return createViewFromResource(inflater, position, convertView, parent, layoutId)
}

private fun createViewFromResource(
inflater: LayoutInflater,
position: Int,
convertView: View?,
parent: ViewGroup,
layoutId: Int
): View {
val view: TextView = (convertView ?: inflater.inflate(layoutId, parent, false)) as TextView
view.text = getItem(position) as String
return view
}

override fun getFilter(): Filter = adapterFilter
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package com.skyyo.samples.features.autoComplete

import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.interaction.DragInteraction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.input.pointer.*
import androidx.compose.ui.node.Ref
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastAll
import com.skyyo.samples.utils.OnValueChange
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.abs

private const val WAITING_TIME_BETWEEN_DISMISS_REQUEST_AND_TAP_EVENT = 500L

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AutoCompleteDropdown(
modifier: Modifier,
scrollInteractionSource: InteractionSource,
items: List<String>,
query: String,
isDropdownVisible: Boolean,
onQueryChanged: OnValueChange,
onItemSelected: OnValueChange,
) {
var isDropdownTemporaryHidden by rememberSaveable { mutableStateOf(false) }
val queryInteractionSource = remember { MutableInteractionSource() }
val isFocused by queryInteractionSource.collectIsFocusedAsState()
val isAutoCompleteDropdownVisible = remember(isDropdownVisible, isDropdownTemporaryHidden) {
isDropdownVisible && !isDropdownTemporaryHidden
}
val coroutineScope = rememberCoroutineScope()
val dismissDropdownJob = remember { Ref<Job>() }
val textInputModifier: Modifier = remember {
Modifier
.fillMaxWidth()
.whenTapped {
// toggle dropdown visibility when user tapped on text field
dismissDropdownJob.value?.cancel().also { dismissDropdownJob.value = null }
isDropdownTemporaryHidden = !isDropdownTemporaryHidden
}
}
val focusManager = LocalFocusManager.current
val queryKeyboardActions = remember {
KeyboardActions(onAny = { focusManager.moveFocus(FocusDirection.Next) })
}

if (isFocused) {
LaunchedEffect(Unit) {
scrollInteractionSource.interactions.collect {
// hide dropdown when it's focused and scroll started
if (it is DragInteraction.Start) {
isDropdownTemporaryHidden = true
}
}
}
}

Dropdown(
modifier = modifier,
expanded = isAutoCompleteDropdownVisible,
onDismissRequest = {
dismissDropdownJob.value = coroutineScope.launch(Dispatchers.IO) {
delay(WAITING_TIME_BETWEEN_DISMISS_REQUEST_AND_TAP_EVENT)
isDropdownTemporaryHidden = true
}
},
anchor = {
OutlinedTextFieldWithValueSwitch(
value = query,
modifier = textInputModifier,
interactionSource = queryInteractionSource,
onSelectionChange = {
dismissDropdownJob.value?.cancel().also { dismissDropdownJob.value = null }
},
onValueChange = {
dismissDropdownJob.value?.cancel().also { dismissDropdownJob.value = null }
isDropdownTemporaryHidden = false
onQueryChanged(it)
},
label = { Text("Label") },
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(isAutoCompleteDropdownVisible)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next, autoCorrect = false),
keyboardActions = queryKeyboardActions
)
},
content = { contentModifier ->
Items(
modifier = contentModifier,
items = items,
onNewItemSelected = { newSelectedItem ->
onItemSelected(newSelectedItem)
if (isFocused) focusManager.moveFocus(FocusDirection.Next)
}
)
}
)
}

@Composable
private fun Items(modifier: Modifier, items: List<String>, onNewItemSelected: OnValueChange) {
LazyColumn(
modifier = modifier,
verticalArrangement = Arrangement.Center
) {
this.items(items = items, key = { item -> item }) { item ->
Box(
contentAlignment = Alignment.CenterStart,
modifier = Modifier
.heightIn(min = 48.dp)
.fillMaxWidth()
.clickable { onNewItemSelected(item) }
.padding(horizontal = 16.dp)
) {
Text(text = item)
}
}
}
}

private fun Modifier.whenTapped(action: () -> Unit) = pointerInput(Unit) {
forEachGesture {
awaitPointerEventScope {
var event: PointerEvent
val touchSlop = viewConfiguration.touchSlop
var scrolledDistance = 0f
var isTapAction = true
do {
event = awaitPointerEvent(PointerEventPass.Initial)
// if more than one pointer on screen, then it's not tap action
if (event.changes.size > 1) isTapAction = false
scrolledDistance += event.changes.firstOrNull()?.positionChange()?.getDistance()
?: 0f
// if scrolled more than touch slop, then it's not tap action
if (abs(scrolledDistance) > touchSlop) isTapAction = false
} while (!event.changes.fastAll { it.changedToUp() })
if (isTapAction) action()
}
}
}
Loading