我在RelativeLayout中有两个视图,它们都填满了屏幕,所以视图B在视图a的顶部。我还定义了一个动画,可以将视图B部分移出屏幕,以显示视图a在下面。动画工作得很好,但我有视图边界不随视图移动的经典问题,所以我用来触发动画的按钮(位于视图B上)只能从其原始位置点击,无论视图B位于何处。我遇到的问题是,动画结束后,当我设置布局参数时,它会导致视图B再次被重新绘制,从动画结束的位置翻译。
作为一个具体的例子,视图B的左边缘初始位置为x = 0,按钮位置为x = 450。当按钮被按下时,动画将视图移动到x = -400。这可以正常工作-视图部分离开屏幕的左侧,按钮现在在x = 50处,所以它仍然在屏幕上。按钮的点击区域仍然在x = 450。现在我在视图B上设置布局参数:
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) viewB.getLayoutParams();
lp.rightMargin = 400;
viewB.setLayoutParams(lp);
一旦设置了新的参数,视图在右侧获得400px的内边距,将整个视图移动到x = -800。按钮的可点击区域现在正好在x = 50,所以看起来我可以让它看起来正确或操作正确。知道我哪里做错了吗?下面是动画的设置方法。
Animation anim = null;
anim = new TranslateAnimation(0, -400, 0, 0);
anim.setAnimationListener(this);
anim.setDuration(duration);
viewB.startAnimation(anim);
我可以通过在动画之前或之后适当地改变布局参数来使事情正常工作:
private int marginOffsets;
public void triggerAnimation(boolean show, offset)
{
int curX = 0;
int newX = 0;
Animation anim = null;
this.showingPanel = show;
if(show)
{
curX = 0 - offset;
android.widget.RelativeLayout.LayoutParams lp = new android.widget.RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lp.rightMargin = 0;
rootPanel.setLayoutParams(lp);
}
else
{
newX = 0 - offset;
}
marginOffsets = newX < 0 ? 0 - offset : offset;
anim = new TranslateAnimation(curX, newX, 0, 0);
anim.setAnimationListener(this);
anim.setDuration(duration);
startAnimation(anim);
}
public void onAnimationEnd(Animation anim)
{
//This prevents flicker when the view is moving onscreen.
clearAnimation();
if(!showingPanel)
{
//Move the margin to move the actual bounds so click events still work.
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
lp.rightMargin = 0 - marginOffsets;
rootPanel.setLayoutParams(lp);
}
}