Have to click twice to get previous array element

John Smith :

I want to make a gallery app with previous and next button. I made an array of photos. Whenever I reached the last photo, I have to click the previous button twice to get the previous photo. And also when I get to the first photo, I have to click the next button twice to get to the next photo. My code:

public class MainActivity extends AppCompatActivity {

    ImageView ivphoto;
    Button btnext;
    Button btprevious;
    int a=0;
    int photoarray[]={R.drawable.cat, R.drawable.dog, R.drawable.duck, R.drawable.elephant, R.drawable.monkey, R.drawable.pig, R.drawable.rabbit, R.drawable.tiger};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ivphoto = findViewById(R.id.ivphoto);
        btnext = findViewById(R.id.btnext);
        btprevious = findViewById(R.id.btprevious);

        btnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ivphoto.setImageResource(photoarray[a]);
                a++;
                if (a==8){
                    a=7;
                    Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btprevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ivphoto.setImageResource(photoarray[a]);
                a--;
                if(a==-1){
                    a=0;
                    Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Any one please help me with this. Thanks.

Mosius :

Try this code in next button:

if(a == photoarray.lenght - 1)
    Toast.makeText(MainActivity.this, "This is last photo", Toast.LENGTH_SHORT).show();
else
    ivphoto.setImageResource(photoarray[++a]);

And this code in back button:

if(a == 0)
    Toast.makeText(MainActivity.this, "This is first photo.", Toast.LENGTH_SHORT).show();
else
    ivphoto.setImageResource(photoarray[--a]);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84201&siteId=1