Issue
I need to be able to press multiple buttons at the same time in my app but I cannot figure out how to implement it. The standard Pressable component and onPress, onPressIn, onPressOut functions don't work since only 1 button can be pressed at a time.
I have seen previous answers like "https://stackoverflow.com/questions/42776490/how-do-i-enable-touch-on-multiple-buttons-simultaneously-in-react-native/42779656#42779656". They suggest that I should use a View component and onTouchStart, onTouchEnd functions, but those aren't working either like many have pointer out in the comments. Whenever I start pressing a button, it registers it, but when I try to press anywhere else on the screen (outside the pressed view component and even other components), it re-registers the same initial button press.
<View
onTouchStart={() => console.log(1)}
style={{ width: 50, height: 50, backgroundColor: 'red' }}
/>
<View
onTouchStart={() => console.log(2)}
style={{ width: 50, height: 50, backgroundColor: 'red' }}
/>
For this code, if I press the first button, 1 is logged into the console and pressing anywhere on the screen after that logs 1 into the console once again.
UPDATE: I just tested it on iOS and it works fine, so the issue is only on Android. It seems like the touch response region expands to the entire screen when holding down on a view and I can't find a way to limit it to the view itself.
Solution
I ended up using GestureDetector from react-native-gesture-handler and implemented my own custom Pressable component.
Note that this code is from 2021, so there might have been some updates to the package and how it works. I would suggest reading the documentation instead, but here is what I had anyways.
import React, { useState } from 'react';
import { View } from 'react-native';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
export default function CustomPressable({
children,
onBegin,
onEnd,
maxDuration = 100000,
}) {
const [isPressed, setPressed] = useState(false);
const tapGesture = Gesture.Tap()
.maxDuration(maxDuration)
.onBegin(() => {
setPressed(true);
onBegin();
})
.onEnd(() => {
setPressed(false);
onEnd();
});
return (
<GestureDetector gesture={tapGesture}>
<View style={isPressed && { backgroundColor: 'rgba(255,255,255,0.5)' }}>
{children}
</View>
</GestureDetector>
);
}
Answered By - Moaaz Assali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.