2014-01-14 72 views
1

我在我的代码中实施滑动操作以更改背景图像。但是当我运行我的应用程序的时候就崩溃我不知道我的代码有什么问题。实施刷卡时应用程序崩溃

代码 -

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; 
     } 

     } 

} 
+0

你可以发布日志吗? –

+0

当它被创建或刷卡后它会崩溃吗?你可以发布日志吗? –

回答

3
RelativeLayout layout1; 

你已宣告但没有初始化的布局1,id为初始化和尝试。

+0

看起来够合理! –

+0

从右向左滑动工作,但从左到右不工作。 –

+0

@JohnR这应该是个问题。任何如何看到这个链接代码从左到右,从左到右滑动.https://stackoverflow.com/a/12938787/1937802 –

0

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

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