0

I have a array of cities -

String[] cities = { "Riyadh", "Jubail", "Jeddah", "Madinah",
        "Tabuk","Bangalore","Chennai","Pune" };

I am displaying them in a list that has three textview(fixed) .
This means we are going to display three cities at a time.
Here is the method to display the cities.


void setUpCityList(int iCity) {
    tvOneCity.setText(cities[iCity]);
    tvTwoCity.setText(cities[iCity + 1]);
    tvThreeCity.setText(cities[iCity + 2]);
}


When the user swipes up ,i am incrementing the index and the user swipes down i am decrementing the index.

void swipeUp()
{
    iCity++;
    setUpCityList(iCity);
}

void swipeDown()
{
    iCity--;
    setUpCityList(iCity);
}


I want to give this list a endless scroll functionality .
That means if the user swipes up - and list reaches the last three elements , it should again start from first element.

Example -
1. Current display - Last three elements - "Bangalore","Chennai","Pune"
2. Swipe up -- Display should be - Chennai , Pune , Riyadh

How can i achieve this functionality .
This is more of a programming question .
Any Help will be highly appreciated.

Anukool
  • 5,301
  • 8
  • 29
  • 41

3 Answers3

4

You just need to change the indexing in your method:

void setUpCityList(int iCity) {
    int length = cities.length;   

    tvOneCity.setText(cities[iCity % length]);
    tvTwoCity.setText(cities[(iCity + 1) % length]);
    tvThreeCity.setText(cities[(iCity + 2) % length]);
}

Once the iCity or iCity + 1, etc, reaches the length, actual index will automatically become 0. And for values less than length, it will behave normally, as if there was no modulus operator.

This way you can create a cycle of as much item you want. So, it's a generalized and extensible solution.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0
void swipeUp()
{   if(iCity == cities.length()){
        iCity = 0;
        setUpCityList(iCity++);

    }
    else{
        iCity++;
        setUpCityList(iCity);
    }
}

Try something like this.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

you can try this:

void swipeUp()
{
iCity++;
if ( iCity > urMaxlength){
   iCity =0;
}
setUpCityList(iCity);
}

void swipeDown()
{
iCity--;
if ( iCity < urMinlength){
   iCity =urMaxlength;
}
setUpCityList(iCity);
}
user1969053
  • 1,750
  • 1
  • 12
  • 12