我試過在我的項目中添加一些拖拽&拖放機制。 我這樣做的方式基本上每次發生觸摸事件時都會發生兩個操作:
首先,根據觸摸事件
更新我在onLayout()中使用的參數,調用requestLayout()進行刷新。
(我嘗試過使用OnTouchListener方法和View的onTouchEvent(),如代碼中所示)Android:在OnTouchListener方法中調用requestLayout()時發生撕裂效應?一種解決方法?
問題是,屏幕上的結果不是很好。 它給的感覺像有一些撕裂問題的拖累視圖(新的繪圖較早結束前開始)
的代碼看起來像這樣(簡化版本):
public class DragAndDrop extends ViewGroup
{
View touchView;
float touchX;
float touchY;
static int W = 180;
static int H = 120;
public DragAndDrop(Context context)
{
super(context);
touchView = new View(context);
touchView.setBackgroundColor(0xaaff9900);
addView(touchView);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
float width = r - l;
float height = b - t;
int centerX = (int) (touchX - W/2);
int centerY = (int) (touchY - H/2);
touchView.layout(centerX, centerY, centerX + W, centerY + H);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
touchX = event.getX();
touchY = event.getY();
requestLayout();
return true;
}
}
調查後發現問題是用requestLayout()方法裏面的這個touchListener方法。
我把這個調用移動到一個定時器,它定期觸發它,結果好得多。
沒有其他人經歷過,並知道更好的方式做到這一點,而不使用計時器?
我寧願避免一直刷新更多實際需要的時間。
感謝您的幫助!