John Smith :
Quiero hacer una galería de aplicación con el botón anterior y siguiente. Hice una array
de 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]);