【问题标题】:How can i handle array index out of bound?如何处理超出范围的数组索引?
【发布时间】:2012-06-04 16:15:48
【问题描述】:

我在网格视图中有一个图像列表。当我单击它以全屏心情显示的图像时,通过触摸将一个图像更改为另一个只是增加位置。这是 onTouchListener 的代码

private int position=0;
imageView.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event)   
    {  
        if(event.getAction() == MotionEvent.ACTION_DOWN)  
        {  
              position++;
              if( v == findViewById( R.id.full_image_view ))   
              { 
                   imageView.setImageResource(imageAdapter.mThumbIds[position]);
              }
        }
        return false; 
    }
}); 

在最后一张图片中,它显示“它已意外停止”的错误。我该如何处理索引绑定的数组?

【问题讨论】:

    标签: android arrays indexoutofboundsexception


    【解决方案1】:

    您正在尝试获取不在您的数组中的索引。您的position must be less than array.length

     if( v == findViewById( R.id.full_image_view ))
                  {
                      if(position < imageAdapter.mThumbIds.length){
    
                        imageView.setImageResource(imageAdapter.mThumbIds[position]);
    
                     }
                   }
    

    【讨论】:

      【解决方案2】:

      在尝试访问数组中的元素之前,检查索引是否有效(在0array.size - 1 之间)。

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2012-11-12
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多