2017-11-25 130 views
0

您好我使用drag'n下降選項而言,我採用了android工作室3 & SDK 26 當我到觸摸事件中,我得到錯誤信息寫一個應用程序: java.lang.ClassCastException :android.widget.LinearLayout $的LayoutParams不能轉換到android.widget.RelativeLayout $的LayoutParams 那代碼:拖放功能onTouch事件失敗

private View.OnTouchListener OnTouchListener() { 

    return new View.OnTouchListener() { 
     @SuppressLint("ClickableViewAccessibility") 
     @Override 
     public boolean onTouch(View view, MotionEvent motionEvent) { 

      final int x = (int) motionEvent.getRawX(); 
      final int y = (int) motionEvent.getRawY(); 
      switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) { 

       case MotionEvent.ACTION_DOWN: 
        RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) 
          view.getLayoutParams(); 
        xDelta = x - lParams.leftMargin; 
        yDelta = y - lParams.topMargin; 
        break; 

       case MotionEvent.ACTION_UP: 
        break; 

       case MotionEvent.ACTION_MOVE: 
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view 
          .getLayoutParams(); 
        layoutParams.leftMargin = x - xDelta; 
        layoutParams.topMargin = y - yDelta; 
        layoutParams.rightMargin = 0; 
        layoutParams.bottomMargin = 0; 
        view.setLayoutParams(layoutParams); 
        break; 
      } 
      mainlayout.invalidate(); 
      return true; 
     } 
    }; 
} 

我之前使用的代碼,它的工作,我無法理解什麼是錯在這裏。

回答

0

基於錯誤消息的問題無關,與拖拽,它看起來像這部分代碼:

RelativeLayout.LayoutParams lParams =(RelativeLayout.LayoutParams) view.getLayoutParams() ;

RelativeLayout.LayoutParams的LayoutParams =(RelativeLayout.LayoutParams)視圖 .getLayoutParams();

應改爲:

LinearLayout.LayoutParams lParams =(LinearLayout.LayoutParams) view.getLayoutParams();

LinearLayout.LayoutParams的LayoutParams =(LinearLayout.LayoutParams)視圖 .getLayoutParams();

你沒有把你的XML,但我假設「視圖」的父母是一個LinearLayout的權利?

+0

<?XML版本= 「1.0」 編碼= 「UTF-8」?>

+0

其相對佈局... –

+0

好吧,我認爲在這種情況下觸摸傳播到你認爲的孩子。如果您對特定視圖內的觸摸感興趣,也許應該在使用RelativeLayout.LayoutParams layoutParams之前添加一種測試。像if(view ==我specefic視圖)然後把其餘的代碼。 – Jaja