【问题标题】:Scroll to last item in flatList - Android滚动到 flatList 中的最后一项 - Android
【发布时间】:2020-12-05 18:40:56
【问题描述】:

我正在使用 FlatList - React Native 实现一个 Slider,

我有两个案例

  • 按下可转到下一张幻灯片
  • 按下可跳过并转到 Slider 中的最后一项

所以首先我应该知道我所在的当前索引并基于它 我滚动到下一项,

为了获得这个索引,我应该使用onMomentumScrollEnd,但问题是,它不会在 Android 中触发

   onMomentumScrollEnd={(ev) => {
          offsetRef.current = ev.nativeEvent.contentOffset.x;
          console.log('ev', ev.nativeEvent.contentOffset.x);
          console.log(' offsetRef.current', offsetRef.current);
    }}


const NextButton = () => {
  return (
    <TouchableOpacity
      onPress={() =>
        flatListRef.current.scrollToOffset({
          animated: true,
          offset: offset.current + width,
        })
      }>
      <Text style={{color: '#fff', fontSize: 16}}>Next</Text>
    </TouchableOpacity>
  );
};


const _renderSkipButton = () => {
    return (
      <AnimatedButton
        onPress={() => {
          // animation();
          // setDoneBtn((prev) => !prev);
          flatListRef.current.scrollToIndex({
            animated: true,
            index: data.length - 1, // Not work!
          });
        }}
        style={[styles.buttonCircle, {transform: [{translateY: skipButton}]}]}>
        <Text>skip</Text>
      </AnimatedButton>
    );
  };




 <Animated.FlatList
        data={data.reverse()}
        keyExtractor={(item) => item.title}
        horizontal
        ref={flatListRef}
        showsHorizontalScrollIndicator={false}
        pagingEnabled
        scrollEventThrottle={16}
        contentContainerStyle={{
          paddingBottom: 100,
          flexDirection: 'row-reverse',
        }}
        onScroll={Animated.event(
          [{nativeEvent: {contentOffset: {x: scrollX}}}],
          {useNativeDriver: false},
        )}
        onMomentumScrollEnd={(ev) => {
          const index = Math.round(ev.nativeEvent.contentOffset.x / ITEM_WIDTH);
          const newIndex = I18nManager.isRTL ? data.length - index - 1 : index;
          indexItem.current = newIndex;
          console.log('onMomentumScrollEnd', newIndex);
        }}
        renderItem={....}
       />

Live

【问题讨论】:

  • 为什么要使用偏移量来表示上一个/下一个,而使用索引来表示跳过?
  • @J.Doe for skip 我去最后一个索引它的工作将(我将索引 0)因为我的应用程序是 RTL,对于下一个 prev,我只是尝试索引和偏移但是没有按预期工作!

标签: android react-native react-native-android react-native-flatlist


【解决方案1】:

onMomentumScrollEnd 在您用手指滑动时调用,我认为您需要手动管理。

【讨论】:

  • 不是真的,上面的代码在 iOS 中运行良好,我猜这是一个错误,在下一个按钮中我滚动到基于当前 FlatList 偏移量的偏移量,但由于 onMomentumScrollEnd 没有触发我不能获得新的偏移量,这就是为什么下一个按钮不起作用并卡在第二张幻灯片中的原因:)
猜你喜欢
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 2021-01-18
  • 2016-01-22
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多