如何将多个手势识别器添加到TextSpan?
我想将TapGestureRecognizer和LongPressGestureRecognizer都添加到 TextSpan.现在,我可以添加一个,但不能两个都添加.
I'd like to add both a TapGestureRecognizer and a LongPressGestureRecognizer to a TextSpan. Right now I can add either one, but not both.
我已经研究了GestureDetector类,并希望用它包装TextSpan,但是RichText元素仅接受TextSpans,而不接受窗口小部件.
I've looked into the GestureDetector class and wanted to wrap TextSpan with it, but the RichText element only accepts TextSpans and not Widgets.
这就是我现在拥有的:
TextSpan(
text: "some text",
recognizer: TapGestureRecognizer()
..onTap = () { print('tapped'); }
)
我想在该代码的某处添加 .. onLongPress
.
And I want to add ..onLongPress
somewhere in that code.
最后,两个手势都应在单个文本跨度上起作用.
At the end both gestures should work on the single text span.
似乎无法在TextSpan中添加多个GestureRecognizer,但这是仅使用TapGestureRecognizer并使用使用计时器使用onTapUp和onTapDown来检测点击并模拟长时间点击:
It doesn't seem to be possible to add more than one GestureRecognizer to a TextSpan, but here is a workaround for your case with just the TapGestureRecognizer and using the onTapUp and onTapDown to detect a tap and to simulate a long tap, using a Timer:
TapGestureRecognizer _tapGestureRecognizer;
Timer _timer;
@override
void initState() {
super.initState();
_initRecognizer();
}
_initRecognizer() {
_tapGestureRecognizer = TapGestureRecognizer();
_tapGestureRecognizer.onTapUp = (_) {
if (_timer != null && _timer.isActive) {
print('Tap');
_timer.cancel();
}
};
_tapGestureRecognizer.onTapDown = (_) {
_timer = Timer(Duration(seconds: 1), () {
print('Long Tap');
});
};
}
@override
void dispose() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.all(16.0),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: "This is some text.",
recognizer: _tapGestureRecognizer,
style: Theme.of(context).textTheme.title,
),
TextSpan(
text:
"Another piece of text. Another piece of text. Another piece of text. Another piece of text.",
style: Theme.of(context).textTheme.title,
),
],
),
),
),
);
}