初学者到Android ...在我的应用程序中,我需要显示上一个和下一个图像..我来到这里,但图像被洗牌,没有得到适当的通过单击上一个和下一个按钮来下一个图像....这里是我的代码...
public class MainActivity extends Activity implements OnClickListener{
ImageButton ib_left_arrow, ib_right_arrow;
ImageView slidingimage;
Animation rotateimage;
public int currentimageindex = 0;
private int[] IMAGE_IDS = { R.drawable.image1, R.drawable.image2,
R.drawable.image3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movies);
ib_left_arrow = (ImageButton) findViewById(R.id.iv_left_arrow);
ib_right_arrow = (ImageButton) findViewById(R.id.iv_right_arrow);
ib_left_arrow.setOnClickListener(this);
ib_right_arrow.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.iv_left_arrow:
slidingimage = (ImageView) findViewById(R.id.ImageView3_Left);
slidingimage.setBackgroundResource(IMAGE_IDS[currentimageindex% IMAGE_IDS.length]);
currentimageindex--;
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_left);
slidingimage.startAnimation(rotateimage);
break;
case R.id.iv_right_arrow:
slidingimage = (ImageView) findViewById(R.id.ImageView3_Left);
slidingimage.setBackgroundResource(IMAGE_IDS[currentimageindex % IMAGE_IDS.length]);
currentimageindex++;
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_right);
slidingimage.startAnimation(rotateimage);
break;
}
}
}
任何想法???
答案 0 :(得分:2)
您的代码存在缺陷。您的索引从0开始。
如果我第一次与您的应用互动时按左箭头,则索引将变为-1。当您尝试使用-1模数长度的数组从数组中获取值时,它将返回负值。
这可能导致您从数组中获取错误的值,因此可能会显示错误的图像。
一个简单的解决方法是在索引为0并按下左键时使索引翻转:
case R.id.iv_left_arrow:
if(currentImageIndex == 0)
currentImageIndex = IMAGE_IDS.length - 1 ;
那应该解决它。
答案 1 :(得分:1)
尝试从代码中删除模运算符
switch (v.getId()) {
case R.id.iv_left_arrow:
// should not execute if it is on the first item
if (currentimageindex > 0) {
currentimageindex--;
slidingimage = (ImageView) findViewById(R.id.ImageView3_Left);
slidingimage.setBackgroundResource(IMAGE_IDS[currentimageindex]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_left);
slidingimage.startAnimation(rotateimage);
}
break;
case R.id.iv_right_arrow:
// should not execute if it's on the last item
if (currentimageindex < IMAGE_IDS.length) {
currentimageindex++;
slidingimage = (ImageView) findViewById(R.id.ImageView3_Left);
slidingimage.setBackgroundResource(IMAGE_IDS[currentimageindex]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_right);
slidingimage.startAnimation(rotateimage);
}
break;
没有对此进行测试,但这可以解决您的问题。
我建议您使用这种转换图像的方法,因为您将来会遇到问题。而是使用ViewPager
。此控件专门用于执行此操作。您还可以查看ViewFlipper
控件。这两个控件可帮助您通过Adapter
定义图像列表以及回收,如果您要获得大量图像,这非常重要。