简书链接:setTransX带来的弊端以及解决办法2种
文章字数:275,阅读全文大约需要1分钟
经过修复之后处理的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| private void performMove(String s, float distanceX, float distanceY) { float translationX = this.getTranslationX() + distanceX; float translationY = this.getTranslationY() + distanceY; //translationX是相对自身之前移动了多少,如果向上,为负值向下为正, 同样的 向左为正,那么view的位置可能不确定,qssq说,这就要用getX getY来判断了 if (translationX < 0) { translationX = 0; }
// Prt.w(TAG, " ACTION_MOVE,will settransX:" + translationX + ",will transY:" + translationY + ",beforeTranslationX:" + this.getTranslationX() + ",transY:" + this.getTranslationY() + ",distnceX:" + distanceX + ",distanceY:" + distanceY); this.setTranslationX(translationX);//getx 是父view的左边 gety父亲的顶部距离 getTranx 是相对于原来位置的偏移 this.setTranslationY(translationY); if (BuildConfig.DEBUG) {//,currentTranslationY:-1739.7078的时候看不见了 Prt.w(TAG, "currentTraxnX:" + translationX + ",currentTranslationY:" + translationY + ",x:" + this.getX() + ",y:" + this.getY()); } ViewGroup parent = (ViewGroup) getParent();
if (this.getX() < 0) { this.setX(0); } else if (this.getX() + this.getWidth() > parent.getWidth()) {
float fixX = parent.getWidth() - this.getWidth();//这样写不行,因为get
Log.w(TAG, "fixX:" + fixX + ",this.Width:" + this.getWidth() + ",parentWidth:" + parent.getWidth() + ",thjs.x" + this.getX()); this.setX(fixX); }
if (this.getY() < 0) { this.setY(0); } else if (this.getY() + this.getHeight() > parent.getHeight()) { this.setY(parent.getHeight() - this.getHeight()); }
if (onMoveListener != null) { onMoveListener.onTransMove(this.getTranslationX(), this.getTranslationY()); }
}
|
之后还是觉得setX 更好使用,更好的确定边界越界问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| private void performMove(String s, float distanceX, float distanceY) { float willX = this.getX() + distanceX; float willY = this.getY() + distanceY; //translationX是相对自身之前移动了多少,如果向上,为负值向下为正, 同样的 向左为正,那么view的位置可能不确定,qssq说,这就要用getX getY来判断了 if (willX < 0) { willX = 0; } ViewGroup parent = (ViewGroup) getParent(); if (willX < 0) { this.setX(0); } else if (willX + this.getWidth() > parent.getWidth()) {
float fixX = parent.getWidth() - this.getWidth();//这样写不行,因为get Log.w(TAG, "fixX:" + fixX + ",this.Width:" + this.getWidth() + ",parentWidth:" + parent.getWidth() + ",thjs.x" + this.getX()); willX = fixX; } if (willY < 0) { willY = 0; } else if (willY + this.getHeight() > parent.getHeight()) { willY = parent.getHeight() - this.getHeight(); } setX(willX); setY(willY);
if (onMoveListener != null) { onMoveListener.onTransMove(willX,willY); }
}
|