Que hacer clic dos veces para obtener anterior elemento de la matriz

John Smith :

Quiero hacer una galería de aplicación con el botón anterior y siguiente. Hice una arrayde las fotos. Cada vez que llegué a la última foto, tengo que hacer clic en el botón anterior dos veces para conseguir la foto anterior. Y también cuando llegue a la primera foto, tengo que hacer clic en el botón Siguiente dos veces para llegar a la siguiente foto. Mi código:

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();
                }
            }
        });
    }
}

Cualquiera que me ayuda por favor con esto. Gracias.

Moisés;

Prueba este código en el siguiente botón:

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

Y este código en el botón de regreso:

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

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=195831&siteId=1
Recomendado
Clasificación