Scroll to position ListView android

Contents

  • 1 Scroll to a Specific Item in ScrollView ListView
  • 2 How to Scroll to the Specific item?
  • 3 To Make a React Native App
  • 4 Code
    • 4.1 App.js
  • 5 To Run theReact Native App
  • 6 Output Screenshots
  • 7 Output in Online Emulator

Scroll to a Specific Item in ScrollView ListView

In thisexample, we will see how to Scroll to a Specific Item in ScrollView ListView. If you are not clear with the topic then you can imagine you have made a list using scroll view something like the example ofMaking a List using ScrollViewand now you want to scroll to a specific item in the ScrollView list. For example, you are searching any data from the ScrollView List array and found the matching data on index 7 in the array now you want to scroll the list to item 7, In this situation, you can take the help from this example.

Note: We are not going to use any external library to do this. We are going to use the onLayout prop of the View component provided by React Native.

In this example, we will create a List using Scroll View to hold the data, a TextInput and a button to take the index as input and scroll to the item.

How to Scroll to the Specific item?

1. To scroll to the specific item first we will make a blank array to store the X and Y coordinates of the item.

const [dataSourceCords, setDataSourceCords] = useState([]);

2. While rendering the item we will store the X and Y location of the item in the array. These locations can be found using theonLayout prop of the view Component. We have also added a reference to the ScrollView.

<View key={key} style={styles.item} onLayout={(event) => { const layout = event.nativeEvent.layout; dataSourceCords[key] = layout.y; setDataSourceCords(dataSourceCords); console.log(dataSourceCords); console.log('height:', layout.height); console.log('width:', layout.width); console.log('x:', layout.x); console.log('y:', layout.y); }}> <Text style={styles.itemStyle} onPress={() => getItem(item)}> {item.id}. {item.title} </Text> <ItemSeparatorView /> </View>

3. After the 2nd step, you have a ScrollView list with the data listed from the array and an array with the name arr which holds the X and Y location of the item on the same index as the data array has. Now, whenever we want to scroll to a specific location we can usescrollTo which is a property of ScrollView. In this, we have to pass the X and Y location to scroll and animated (True/False).

ref.scrollTo({ x: 0, y: dataSourceCords[scrollToIndex - 1], animated: true, });

That is it.

Now you can see the full example code below.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.Xreact-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Code

Now Open App.js in any code editor and replace the code with the following code

App.js

// Scroll to a Specific Item in ScrollView List View // https://aboutreact.com/scroll_to_a_specific_item_in_scrollview_list_view/ // import React in our code import React, {useState, useEffect} from 'react'; // import all the components we are going to use import { SafeAreaView, View, ScrollView, StyleSheet, Text, TouchableOpacity, TextInput, } from 'react-native'; const App = () => { const [dataSource, setDataSource] = useState([]); const [scrollToIndex, setScrollToIndex] = useState(0); const [dataSourceCords, setDataSourceCords] = useState([]); const [ref, setRef] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); setDataSource(responseJson); }) .catch((error) => { console.error(error); }); }, []); const scrollHandler = () => { console.log(dataSourceCords.length, scrollToIndex); if (dataSourceCords.length > scrollToIndex) { ref.scrollTo({ x: 0, y: dataSourceCords[scrollToIndex - 1], animated: true, }); } else { alert('Out of Max Index'); } }; const ItemView = (item, key) => { return ( // Flat List Item <View key={key} style={styles.item} onLayout={(event) => { const layout = event.nativeEvent.layout; dataSourceCords[key] = layout.y; setDataSourceCords(dataSourceCords); console.log(dataSourceCords); console.log('height:', layout.height); console.log('width:', layout.width); console.log('x:', layout.x); console.log('y:', layout.y); }}> <Text style={styles.itemStyle} onPress={() => getItem(item)}> {item.id}. {item.title} </Text> <ItemSeparatorView /> </View> ); }; const ItemSeparatorView = () => { return ( // Flat List Item Separator <View style={styles.itemSeparatorStyle} /> ); }; const getItem = (item) => { // Function for click on an item alert('Id : ' + item.id + ' Title : ' + item.title); }; return ( <SafeAreaView style={{flex: 1}}> <View style={styles.container}> <View style={styles.searchContainer}> <TextInput value={ String( scrollToIndex ? scrollToIndex : 0 ) } numericvalue keyboardType={'numeric'} onChangeText={(scrollToIndex) => { setScrollToIndex( parseInt( scrollToIndex != '' ? scrollToIndex : 0 ), ); }} placeholder={'Enter the index to scroll'} style={styles.searchInput} /> <TouchableOpacity activeOpacity={0.5} onPress={scrollHandler} style={styles.searchButton}> <Text style={styles.searchButtonText}> Go to Index </Text> </TouchableOpacity> </View> {/* List Item as a function */} <ScrollView ref={(ref) => { setRef(ref); }}> {dataSource.map(ItemView)} </ScrollView> </View> </SafeAreaView> ); }; const styles = StyleSheet.create({ container: { backgroundColor: 'white', }, itemStyle: { padding: 10, }, itemSeparatorStyle: { height: 0.5, width: '100%', backgroundColor: '#C8C8C8', }, searchContainer: { flexDirection: 'row', backgroundColor: '#1e73be', padding: 5, }, searchInput: { flex: 1, backgroundColor: 'white', padding: 10, }, searchButton: { padding: 15, backgroundColor: '#f4801e', }, searchButtonText: { color: '#fff', }, }); export default App;

To Run theReact Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

Scroll to position ListView android
Scroll to position ListView android
Scroll to position ListView android
Scroll to position ListView android
Scroll to position ListView android

Output in Online Emulator

This is how you can Scroll to a Specific Item in ScrollView ListView. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it.