Reputation: 1042
I have two button and an ImageView. When I click Next button it goes to next image from drawable folder. But the Previous button does not work. I don't know why, I think my logic is correct. Here's my code:
public class Photo_gallery extends Activity implements OnClickListener{
Button next,previous;
ImageView slika;
int a = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
InicijalizujVarijable();
}
private void InicijalizujVarijable() {
next = (Button) findViewById(R.id.bNext);
previous = (Button) findViewById(R.id.bPrevious);
slika = (ImageView) findViewById(R.id.imageView1);
next.setOnClickListener(this);
previous.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bNext:
if (a == 0)
{
slika.setImageResource(R.drawable.p2);
a = 1;
}
else if (a == 1)
{
slika.setImageResource(R.drawable.p3);
a = 2;
}
else if (a == 2)
{
slika.setImageResource(R.drawable.p4);
a = 3;
.
.
.
.
}
else if (a == 56)
{
startActivity(new Intent("com.example.apps.MENU"));
finish();
}
break;
case R.id.bPrevious:
a--;
next.performClick();
break;
}
}
Upvotes: 0
Views: 91
Reputation: 4860
Use
onClick(next);
instead of
next.performClick();
And also try to save your image's ids in an array then get from it up to "a" value, not write 56 if statement.
Upvotes: 0
Reputation: 4001
Why don't you do it by making it a function
public void onClick(View v) {
switch (v.getId()){
case R.id.bNext:
///function calling
a++;
setImage(a);
break;
case R.id.bPrevious:
if(a>0)
{
a--;
setImage(a);
break;
}
}
}
private void setImage(int a)
{
if (a == 0)
{
slika.setImageResource(R.drawable.p2);
}
else if (a == 1)
{
slika.setImageResource(R.drawable.p3);
}
else if (a == 2)
{
slika.setImageResource(R.drawable.p4);
.
.
.
.
}
else if (a == 56)
{
startActivity(new Intent("com.example.apps.MENU"));
finish();
}
}
Edit
Increment and decrements are done by the onClick method with a++
and a--
remember start your int a =-1
. But the default picture will be null until you click on NextPicture
Its always better to you a variable dynamically ie. increasing with ++
or --
rather than initializing it with a value. like a=21
. Not preferred.
Upvotes: 2
Reputation: 55
Try this :
public class MainActivity extends Activity implements OnClickListener{
private int[] IMAGE_IDS = { R.drawable.image1, R.drawable.image2,
R.drawable.image3};
int imglength=IMAGE_IDS.length;
int img_position;
ImageView slidingimage;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.iv_left_arrow:
img_position--;
break;
case R.id.iv_right_arrow:
img_position++;
break;
}
if(img_position < 0) img_position = imglength-1;
if(img_position >= imglength) img_position = imglength -1;
slidingimage.setImageResource(IMAGE_IDS[img_position]);
}
}
Upvotes: 0