如何为ImageView设置图像?

时间:2015-04-27 21:15:45

标签: android android-imageview android-drawable

我正在尝试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设置图像(或背景)?

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

尝试使用setImageResource方法代替setBackground

image.setImageResource (R.drawable.img2);