实施滑动时应用程序崩溃

时间:2014-01-14 07:39:19

标签: android swipe

我正在我的代码中实现滑动操作来更改背景图像。但是,当我运行我的应用程序崩溃。我不知道我的代码中有什么不对。

代码 -

public class Types extends Activity{

    RelativeLayout layout1;
    int[] backgroundResId;
    int currentIndex=0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type);
        backgroundResId=new int[]{R.drawable.back,R.drawable.bg,R.drawable.frame1};
        changeBackground();
        ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
        layout1.setOnTouchListener(activitySwipeDetector);

    }


    private void changeBackground(){
         findViewById(R.id.layout1).setBackgroundResource(backgroundResId[currentIndex]);
    }

    public class ActivitySwipeDetector implements View.OnTouchListener {

        static final String logTag = "ActivitySwipeDetector";
        static final int MIN_DISTANCE = 100;
        private float downX, upX;
        private Activity activity;

        public ActivitySwipeDetector(Activity activity){
            this.activity = activity;
        }

        public void onRightToLeftSwipe(){
            Log.i(logTag, "RightToLeftSwipe!");
            currentIndex++;
            if(currentIndex<backgroundResId.length){
                 changeBackground();
            }
        }

        public void onLeftToRightSwipe(){
            Log.i(logTag, "LeftToRightSwipe!");
            if(currentIndex>0){
                changeBackground();
           }
        }

        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()){
                case MotionEvent.ACTION_DOWN: {
                    downX = event.getX();
                    return true;
                }
                case MotionEvent.ACTION_UP: {
                    upX = event.getX();

                    float deltaX = downX - upX;

                    // swipe horizontal?
                    if(Math.abs(deltaX) > MIN_DISTANCE){
                        // left or right
                        if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
                        if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
                    }
                    else {
                            Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
                            return false; // We don't consume the event
                    }


                    return true;
                }
            }
            return false;
        }

        }

}

2 个答案:

答案 0 :(得分:3)

RelativeLayout layout1;

您已声明但未初始化layout1,请使用id初始化它并尝试。

答案 1 :(得分:0)

您必须获取NullPointerException,因为您尚未初始化RelativeLayout实例 layout1 。这样做 -

private void changeBackground()
{
     layout1 = findViewById(R.id.layout1);
     layout1.setBackgroundResource(backgroundResId[currentIndex]);
}