Java 如何强制视图重新计算它';更改父项后的位置
我已经好几天没有这个问题了 这是对我描述的行为的重新表述。请注意,这个问题针对的是一个不太具体的案例,答案可能对许多不同的场景都有用 我将一个芯片从左点移动到右点,并写入原始坐标和新坐标: 所以这是失败的:Java 如何强制视图重新计算它';更改父项后的位置,java,android,android-layout,android-view,Java,Android,Android Layout,Android View,我已经好几天没有这个问题了 这是对我描述的行为的重新表述。请注意,这个问题针对的是一个不太具体的案例,答案可能对许多不同的场景都有用 我将一个芯片从左点移动到右点,并写入原始坐标和新坐标: 所以这是失败的: public void onTouch(View view) { int[] aux = new int[2]; //Get the chip View movingChip = findViewById(R.id.c1); //Write it's co
public void onTouch(View view) {
int[] aux = new int[2];
//Get the chip
View movingChip = findViewById(R.id.c1);
//Write it's coordinates
movingChip.getLocationOnScreen(aux);
((TextView)findViewById(R.id.p1t1)).setText("(" + aux[0] + "," + aux[1] + ")");
//Move it
((LinearLayout)findViewById(R.id.p1)).removeView(movingChip);
((LinearLayout)findViewById(R.id.p2)).addView(movingChip);
movingChip.requestLayout();//#### Adding this didn't solve it
//Write it's coordinates
movingChip.getLocationOnScreen(aux);
((TextView)findViewById(R.id.p2t4)).setText("(" + aux[0] + "," + aux[1] + ")");
}
当我第二次获得坐标时,我获得视图的坐标,就好像它位于新父视图中与旧父视图相同的位置一样
所以,新的顶部,左侧,底部,右侧等等。。。此时不进行计算。
另一方面,我的视图会正确显示,因此这项工作在某个时候会完成。我怎么能强迫这种计算呢
我需要这样做,因为我想触发一个过渡动画我建议使用
OnLayoutChangeListener
来捕捉芯片的移动。当然,您必须将这些侦听器附加到onTouch
事件之外
chip.addOnLayoutChangeListener(new OnLayoutChangeListener()
{
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom)
{
}
});
基于Dalija建议的解决方案
因此,init()是从构造函数调用的;现在我将尝试从那里执行动画,但这是一个不同的故事。我希望它能起作用。该视图。这将导致它重新绘制
postInvalidate
,当您在UI线程下使其无效时使用。请尝试movingView.requestLayout()
。顺便说一句,你正在移动movingView
但你最近读取的坐标来自movingChip
你应该将你的解决方案作为答案发布,而不是作为问题的编辑。我昨天看到了你的编辑,但已经晚了,我没有时间回复。我还建议您添加您的解决方案作为答案,而不是像@Code peedient那样对问题进行编辑。特别是,因为我的答案不是完整的解决方案,而是更多指向正确方向的指针。这是一个好主意,但我如何获得以前的父位置?我想执行这样一个动画://记住,芯片已经位于目标点int deltaX=origCoordinates[0]-坐标[0];int deltaY=原始坐标[1]-目标坐标[1];TranslateAnimation chipMove=新的TranslateAnimation(deltaX,0,deltaY,0);我想我在这里找到了答案,我会看一看并发布答案,如果这是我想要的答案,我会将我的最终解决方案附加到问题上,这比相关问题中建议的解决方案要好,建议覆盖onLayout,我可以通过私有属性跟踪旧位置。
public class ChipView extends ImageView {
private int[] currentLocation = new int[2];
/*.....
* blah,blah,blah
* .....*/
public void init() {
this.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
int[] newLocation = new int[2];
v.getLocationOnScreen(newLocation);
Log.d("New location:", "("+newLocation[0]+","+newLocation[1]+")");
/** Do whatever is needed with old and new locations **/
currentLocation = newLocation;
}
});
}