How to swipe through images with ImageView & ScrollView using Titanium
Here I have an ImageView within the View, which has a series of pictures that you can swipe to transition from one image to the next. But the only thing changing is the image in the ImageView, not the entire view. That means able to swipe left or right and have the first image go out of the view and the second image to come in. And also have a collection of Images in the bottom ScrollView, when you selected an image from the bottom scrollView, that image should be in the main ImageView.
Simply output looks like below images,
Step 1: Create a new project
- Open Titanium Studio.
Create a new project — At the top of the screen click on File
> New
> Mobile App Project
> Alloy
> Default Alloy Project
then click next
.
Step 2: Design UI
Let’s add the following code lines to the index.xml file.
In here there is a Label within the View to display name (here we use Swipe Images) and an ImageView within the View to display image, and bottom of the View there is a scrollView to store series of images.
Step 3: Add styling to the UI
Let’s add the following code lines to index.tss file.
Step 4: Adding images
We need images to show, so we get images from a remote web URL (example: https://rallycoding.herokuapp.com/api/music_albums) using the HTTPClient object.
Note: As shown in the code example below, you declare an HTTPClient
object and pass to it a number of parameters. Of these, the most critical is the onload
callback function. It is the function called when data is returned and available for use. The onerror
callback function is called when there's a network error, such as a timeout.
Following code lines simply show, how to use HTTPClient request to get data.
Here we get the first image from the URL and set it as the main ImageView image.
$.imgMain.image = jsonObject.articles[index].urlToImage
Store all the images from the URL into the imageArray for further use.
for (var i = 0 ,j = jsonObject.articles.length; i < j; i++) {
imageArray.push(jsonObject.articles[i].urlToImage);
}
Step 5: Swipe main ImageView
When we swipe the main ImageView to left or right call the loadImage
function
We have images in our array (imageArray) and set index to 0 in the above code.
Here’s our function:
Step 6: Set ScrollView Images
Loop through our images and then add them to our scrollView within the HTTPClient request onload
callback function.
Step 6.5: Add ScrollView Images click event listener
Add click
event listener to the imageViews in the bottom scrollView, to set image in the main ImageView when you click one of the images from the bottom scrollView.
smallImageView.addEventListener(‘click’, function(e){
$.imgMain.image = e.source.image;
index = e.source.imageIndex;
});
Let’s add the following code lines to index.js file. (Whole code lines explain in above)
References: