How to perform a haptic feedback in Jetpack Compose - android-jetpack-compose

Using jetpack compose, for a clickevent how to perform haptic feedback. I am new to jetpack compose.
This is what i tried -
val hapticFeedback = LocalHapticFeedback
#Composable
fun Tab() {
Row() {
Icon(imageVector = icon, contentDescription = text)
if (selected) {
// i tried both the following ways, none are working.
hapticFeedback.current.performHapticFeedback(
HapticFeedbackType(10)
)
hapticFeedback.current.performHapticFeedback(HapticFeedbackType.TextHandleMove)
....
Spacer(Modifier.width(12.dp))
Text(text.uppercase(Locale.getDefault()))
}
}
}
I am able to see the text when it is getting selected, but not getting a subtle vibrating feedback.

In version rc-01 of Compose you can use only two types of Haptic Feedback: HapticFeedbackType.LongPress or HapticFeedbackType.TextHandleMove.
val haptic = LocalHapticFeedback.current
val context = LocalContext.current
Row(
Modifier.clickable {
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
}
)

Currently (Compose UI 1.1.0-beta03) only LongPress and TextHandleMove are supported via
val haptic = LocalHapticFeedback.current
Button(onClick = {
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
}) { ... }
as #nglauber answer said.
I guess it is because of the multi-platform support for Compose Desktop.
There's another way, however, if you are on Android and you do not need Compose Desktop compatibility, it's fairly easy to use it:
val view = LocalView.current
Button(onClick = {
view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
}) { ... }
The HapticFeedbackConstants class has a lot of constants.

On my phone (and other devices I've tested on) neither LongPress nor TextHandleMove makes the phone vibrate.
We worked around this before we moved to Compose like this:
import android.content.Context
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.accessibility.AccessibilityManager
fun View.vibrate() = reallyPerformHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
fun View.vibrateStrong() = reallyPerformHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
private fun View.reallyPerformHapticFeedback(feedbackConstant: Int) {
if (context.isTouchExplorationEnabled()) {
// Don't mess with a blind person's vibrations
return
}
// Either this needs to be set to true, or android:hapticFeedbackEnabled="true" needs to be set in XML
isHapticFeedbackEnabled = true
// Most of the constants are off by default: for example, clicking on a button doesn't cause the phone to vibrate anymore
// if we still want to access this vibration, we'll have to ignore the global settings on that.
performHapticFeedback(feedbackConstant, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING)
}
private fun Context.isTouchExplorationEnabled(): Boolean {
// can be null during unit tests
val accessibilityManager = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager?
return accessibilityManager?.isTouchExplorationEnabled ?: false
}
For now we still have to use this code and access it from Compose like in Daniele Segato's answer:
#Composable
fun VibratingButton() {
val view = LocalView.current
Button(onClick = {
view.vibrate()
}) { ... }
}

For me, this worked well when the user presses down the button. Using Compose 1.2.0-beta01
val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val hapticFeedback = LocalHapticFeedback.current
LaunchedEffect(key1 = isPressed) {
if (isPressed) {
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
}
}

Add the feedback logic inside the Modifier.clickable {...} applied to the Row

Related

Android dataStore with flow not get update after edit

I'm use DataStore with flow but I cant get any update on the flow when editing DataStore.
Store.kt
private class IStore(private val context: Context): Store {
val eventIDKey = stringPreferencesKey("EventID")
override suspend fun setEventID(eventID: String) {
context.dataStoreSettings.edit { settings ->
settings[eventIDKey] = eventID
}
}
override fun getEventID(): Flow<String> {
return context.dataStoreSettings.data.map { settings -> settings[eventIDKey].orEmpty() }
}
}
and manipulate getEventID() with data from room database in event service
EventService.kt
fun getSelectedEventLive() = store.getEventID()
.onEach { Log.d("EventService", "income new event id $it") }
.flatMapConcat { if(it.isNotBlank()) eventDao.get(it) else flowOf(null) }
onEach called when I collect the data but when updated it's not called again and need to close and open the app to show the latest data
MainViewModel.kt
val selectedEvent = eventService.getSelectedEventLive()
.stateIn(viewModelScope, SharingStarted.Lazily, null)
and use on Compose with this
val currentEvent by mainViewModel.selectedEvent.collectAsState()
Maybe I doing wrong or maybe there is something I miss?
Usually, you want to use flow.collect {...}, since Flow is cold and need to know that it is being collected to start producing new values.
// MainViewModel.kt
private val _selectedEvent = MutableStateFlow<TypeOfYourEvent>()
val selectedEvent: StateFlow<TypeOfYourEvent> = _selectedEvent
init {
viewModelScope.launch {
getSelectedEventLive().collect { it ->
_selectedEvent.value = it
}
}
}
This example should be fine with your composable's code, you still can collect selectedEvent as state.
Yeah i found the solusion its works if i change the flatMapConcat with flatMapLatest in EventService.kt
fun getSelectedEventLive() = store.getEventID()
.filterNot { it.isBlank() }
.flatMapLatest { eventDao.get(it) }

Manually move accessibility focus in Jetpack Compose

With Android View, I'm able to move the focus to a View like so:
fun View.requestAccessibilityFocus() {
requestFocus()
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
}
How do I achieve this in Jetpack Compose?
I tried using FocusRequester but it doesn't seem to do anything:
val lifecycleOwner = LocalLifecycleOwner.current
val requester = FocusRequester()
Box {
...
Image(
...
contentDescription = "My heading",
modifier = Modifier
...
.focusRequester(requester)
)
}
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
requester.requestFocus()
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
I had to add .focusable() and must do so after .focusRequester(focusRequester).
Box {
...
Image(
...
contentDescription = "My heading",
modifier = Modifier
...
.focusRequester(requester)
.focusable()
)
}
This happens because DiposableEffect might be calling during recomposition. You should not request focus during composition. The solution I have found is to request a focus right after the composition. Like this
LaunchedEffect(Unit) {
this.coroutineContext.job.invokeOnCompletion {
focusRequester.requestFocus()
}
}
This makes sure your code will run when the LauchedEffect leaves the composition because it(the coroutine) either got canceled or completed.

How to show keyboard with Jetpack Compose?

How can I slide in the keyboard?
I tried:
val keyboardController: SoftwareKeyboardController? = LocalSoftwareKeyboardController.current
keyboardController?.show()
But it does not work. What am I missing? Maybe some Manifest flags?
To show keyboard in Compose:
val showKeyboard = remember { mutableStateOf(true) }
val focusRequester = remember { FocusRequester() }
val keyboard = LocalSoftwareKeyboardController.current
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = value,
textStyle = MaterialTheme.typography.body2,
onValueChange = { onValueChange(it)},
label = { Text(label) }
)
// LaunchedEffect prevents endless focus request
LaunchedEffect(focusRequester) {
if (showKeyboard.equals(true)) {
focusRequester.requestFocus()
delay(100) // Make sure you have delay here
keyboard?.show()
}
}
Locked for 3 hours. There are disputes about this answer’s content being resolved at this time. It is not currently accepting new interactions.
What's the issue with the official method?
fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
Read more here.
This method works if you just use it like this:
showSoftKeyboard(AndroidView(context))
You could also try eliminating the parameter entirely by placing the AndroidView in the function's body instead.

How to stop Surface from passing through clicks [duplicate]

The below code is for Jetbrains Desktop Compose. It shows a card with a button on it, right now if you click the card "clicked card" will be echoed to console. If you click the button it will echo "Clicked button"
However, I'm looking for a way for the card to detect the click on the button. I'd like to do this without changing the button so the button doesn't need to know about the card it's on. I wish to do this so the card knows something on it's surface is handled and for example show a differently colored border..
The desired result is that when you click on the button the log will echo both the "Card clicked" and "Button clicked" lines. I understand why mouseClickable isn't called, button declares the click handled. So I'm expecting that I'd need to use another mouse method than mouseClickable. But I can't for the life of me figure out what I should be using.
#OptIn(ExperimentalComposeUiApi::class, androidx.compose.foundation.ExperimentalDesktopApi::class)
#Composable
fun example() {
Card(
modifier = Modifier
.width(150.dp).height(64.dp)
.mouseClickable { println("Clicked card") }
) {
Column {
Button({ println("Clicked button")}) { Text("Click me") }
}
}
}
When button finds tap event, it marks it as consumed, which prevents other views from receiving it. This is done with consumeDownChange(), you can see detectTapAndPress method where this is done with Button here
To override the default behaviour, you had to reimplement some of gesture tracking. List of changes comparing to system detectTapAndPress:
I use awaitFirstDown(requireUnconsumed = false) instead of default requireUnconsumed = true to make sure we get even a consumed even
I use my own waitForUpOrCancellationInitial instead of waitForUpOrCancellation: here I use awaitPointerEvent(PointerEventPass.Initial) instead of awaitPointerEvent(PointerEventPass.Main), in order to get the event even if an other view will get it.
Remove up.consumeDownChange() to allow the button to process the touch.
Final code:
suspend fun PointerInputScope.detectTapAndPressUnconsumed(
onPress: suspend PressGestureScope.(Offset) -> Unit = NoPressGesture,
onTap: ((Offset) -> Unit)? = null
) {
val pressScope = PressGestureScopeImpl(this)
forEachGesture {
coroutineScope {
pressScope.reset()
awaitPointerEventScope {
val down = awaitFirstDown(requireUnconsumed = false).also { it.consumeDownChange() }
if (onPress !== NoPressGesture) {
launch { pressScope.onPress(down.position) }
}
val up = waitForUpOrCancellationInitial()
if (up == null) {
pressScope.cancel() // tap-up was canceled
} else {
pressScope.release()
onTap?.invoke(up.position)
}
}
}
}
}
suspend fun AwaitPointerEventScope.waitForUpOrCancellationInitial(): PointerInputChange? {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.changes.fastAll { it.changedToUp() }) {
// All pointers are up
return event.changes[0]
}
if (event.changes.fastAny { it.consumed.downChange || it.isOutOfBounds(size) }) {
return null // Canceled
}
// Check for cancel by position consumption. We can look on the Final pass of the
// existing pointer event because it comes after the Main pass we checked above.
val consumeCheck = awaitPointerEvent(PointerEventPass.Final)
if (consumeCheck.changes.fastAny { it.positionChangeConsumed() }) {
return null
}
}
}
P.S. you need to add implementation("androidx.compose.ui:ui-util:$compose_version") for Android Compose or implementation(compose("org.jetbrains.compose.ui:ui-util")) for Desktop Compose into your build.gradle.kts to use fastAll/fastAny.
Usage:
Card(
modifier = Modifier
.width(150.dp).height(64.dp)
.clickable { }
.pointerInput(Unit) {
detectTapAndPressUnconsumed(onTap = {
println("tap")
})
}
) {
Column {
Button({ println("Clicked button") }) { Text("Click me") }
}
}

Jetpack Compose: Bottom bar navigation not responding after deep-linking

I have setup a bottom bar in my new Jetpack Compose app with 2 destinations. I have tried to follow the samples from Google.
So for example it looks something like this:
#Composable
fun MyBottomBar(navController: NavHostController) {
val items = listOf(
BottomNavigationScreen.ScreenA,
BottomNavigationScreen.ScreenB
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
BottomNavigation {
items.forEach { screen ->
BottomNavigationItem(
onClick = {
navController.navigate(screen.route) {
popUpTo(navController.graph.findStartDestination().id) {
saveState = true
}
launchSingleTop = true
restoreState = true
}
},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
icon = { Icon(imageVector = screen.icon, contentDescription = null) },
label = { Text(stringResource(screen.label)) }
)
}
}
}
This all works fine and I'm able to navigate between the two destinations. However, I also have a deep-link to ScreenB. Once this has been invoked, pressing the ScreenA button seems to do nothing (If I add logging I can see that currentDestination is being repeatedly set to ScreenB) but pressing back returns to the startDestination of ScreenA.
My workaround at the moment is to remove the restoreState = true line from the sample code.
My suspicion is that something about the deep-link is being persisted and although it tries to go to ScreenA the navigation component says that it's got a deep-link pointing to ScreenB so it just goes there. I've tried resetting the activity intent so that it has no flags and no data in the intent, I've even tried changing the intent action type but all to no avail.
I am using Compose 1.0.0-rc02 and Compose Navigation 2.4.0-alpha04.
Am I doing something wrong or is this a bug?
I know you got this code from the official documentation, but I don't think it works well for bottom navigation. It keeps the elements in the navigation stack, so pressing the back button from ScreenB will take you back to ScreenA, which does not seem to me to be the right behavior in this case.
That's why it's better to remove all elements from the stack, so that only one of the tabs is always left. And with saveState you won't lose state anyway. This can be done as follows:
fun NavHostController.navigateBottomNavigationScreen(screen: BottomNavigationScreen) = navigate(screen.route) {
val navigationRoutes = BottomNavigationScreen.values()
.map(BottomNavigationScreen::route)
val firstBottomBarDestination = backQueue
.firstOrNull { navigationRoutes.contains(it.destination.route) }
?.destination
if (firstBottomBarDestination != null) {
popUpTo(firstBottomBarDestination.id) {
inclusive = true
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
And use it like this:
BottomNavigationItem(
onClick = {
navController.navigateBottomNavigationScreen(screen)
},
selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
icon = { Icon(imageVector = screen.icon, contentDescription = null) },
label = { Text(screen.label) }
)
For the same reasons, I wouldn't use deep link navigation in this case. Instead, you process them manually. You can use a view model to not re-process deep link if you leave bottom navigation view and come back:
class DeepLinkProcessingViewModel : ViewModel() {
private var deepLinkProcessed = false
fun processDeepLinkIfAvailable(context: Context): String? {
if (!deepLinkProcessed) {
val activity = context.findActivity()
val intentData = activity?.intent?.data?.toString()
deepLinkProcessed = true
return intentData
}
return null
}
}
And using this view model you can calculate start destination like this:
val context = LocalContext.current
val deepLinkProcessingViewModel = viewModel<DeepLinkProcessingViewModel>()
val startDestination = rememberSaveable(context) {
val deepLink = deepLinkProcessingViewModel.processDeepLinkIfAvailable(context)
if (deepLink == "example://playground") {
// deep link handled
BottomNavigationScreen.ScreenB.route
} else {
// default start destination
BottomNavigationScreen.ScreenA.route
}
}
NavHost(navController = navController, startDestination = startDestination) {
...
}
Or, if you have several navigation elements in front of the bottom navigation and you don't want to lose them with a deep link, you can do it as follows:
val navController = rememberNavController()
val context = LocalContext.current
val deepLinkProcessingViewModel = viewModel<DeepLinkProcessingViewModel>()
LaunchedEffect(Unit) {
val deepLink = deepLinkProcessingViewModel.processDeepLinkIfAvailable(context) ?: return#LaunchedEffect
if (deepLink == "example://playground") {
navController.navigateBottomNavigationScreen(BottomNavigationScreen.ScreenB)
}
}
NavHost(
navController = navController,
startDestination = BottomNavigationScreen.ScreenA.route
) {
findActivity:
fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
Looks like it's finally fixed in the 2.4.0-beta02 release; so it was a bug after all.
I was able to add the saveState and restoreState commands back into my BottomBar (as per the documentation) and following a deep-link I was now still able to click the initial destination.

Resources