我正在尝试ImageView
在触摸动作上滑动图像,但是当我移动到下一张图像时,我收到错误说:
java.lang.NullPointerException:尝试调用虚方法' void android.widget.ImageView.setBackground(android.graphics.drawable.Drawable)' 在null对象引用上 在com.semicolon.www.slider.MainActivity.onTouchEvent(MainActivity.java:48)
以下是代码:
public class MainActivity extends ActionBarActivity {
ImageSwitcher Switch;
ImageView image;
float intialX;
private Cursor cursor;
private int columnIndex, position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch = (ImageSwitcher) findViewById(R.id.imageSwitcher);
image = (ImageView) findViewById(R.id.image);
}
public boolean onTouchEvent(MotionEvent event){
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
intialX = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
if (intialX > finalX) {
Drawable r = getResources().getDrawable(R.drawable.img2);
image.setBackground(r);
}
break;
}
return false;
}
}
那么我如何修复此错误并为ImageView
设置图像(或背景)?
答案 0 :(得分:1)
尝试使用viewPager而不是ImageSwitcher
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
答案 1 :(得分:1)
尝试使用setImageResource
方法代替setBackground
:
image.setImageResource (R.drawable.img2);