gpt4 book ai didi

Android - 在 LinearLayout 或 RelativeLayout 中为 View 的 topMargin/bottomMargin/等设置动画

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:52:40 26 4
gpt4 key购买 nike

我正在尝试创建一个从底部向上滑动的菜单。它从屏幕底部可见的菜单 View 开始,然后单击它会使它向上滑动。我尝试使用 TranslateAnimation,但尽管像素移动了,但菜单的点击区域仍处于与以前相同的位置。所以我认为如果我可以在动画完成后调整菜单的边距,这将实现我想要的。但是,我不知道如何调整边距。

我已经尝试创建一个 LinearLayout.LayoutMargins 对象,然后设置其边距并将其应用于菜单 View (这是一个 LinearLayout),但这并没有'工作。

有什么想法吗?

最佳答案

以下对我有用。首先确定向上(完全可见)或向下(大部分隐藏)菜单的底部边距(倾斜)。

private static final int BOTTOM_MARGIN_UP = -50; // My menu view is a bit too tall.
private static final int BOTTOM_MARGIN_DOWN = -120;

然后,在 onCreate() 中:

menuLinearLayout = (LinearLayout)findViewById(R.id.menuLinearLayout);
setBottomMargin(menuLinearLayout, BOTTOM_MARGIN_DOWN);

upAnimation = makeAnimation(BOTTOM_MARGIN_DOWN, BOTTOM_MARGIN_UP);
downAnimation = makeAnimation(BOTTOM_MARGIN_UP, BOTTOM_MARGIN_DOWN);

Button toggleMenuButton = (Button)findViewById(R.id.toggleMenuButton);
toggleMenuButton.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motionEvent)
{
if (motionEvent.getAction() != MotionEvent.ACTION_DOWN) return false;
ViewGroup.MarginLayoutParams layoutParams =
(ViewGroup.MarginLayoutParams)menuLinearLayout.getLayoutParams();
boolean isUp = layoutParams.bottomMargin == dipsToPixels(BOTTOM_MARGIN_UP);
menuLinearLayout.startAnimation(isUp ? downAnimation : upAnimation);
return true;
}
});

秘诀来了;-)

private TranslateAnimation makeAnimation(final int fromMargin, final int toMargin)
{
TranslateAnimation animation =
new TranslateAnimation(0, 0, 0, dipsToPixels(fromMargin - toMargin));
animation.setDuration(250);
animation.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationEnd(Animation animation)
{
// Cancel the animation to stop the menu from popping back.
menuLinearLayout.clearAnimation();

// Set the new bottom margin.
setBottomMargin(menuLinearLayout, toMargin);
}

public void onAnimationStart(Animation animation) {}

public void onAnimationRepeat(Animation animation) {}
});
return animation;
}

我使用了两个效用函数:

private void setBottomMargin(View view, int bottomMarginInDips)
{
ViewGroup.MarginLayoutParams layoutParams =
(ViewGroup.MarginLayoutParams)view.getLayoutParams();
layoutParams.bottomMargin = dipsToPixels(bottomMarginInDips);
view.requestLayout();
}

private int dipsToPixels(int dips)
{
final float scale = getResources().getDisplayMetrics().density;
return (int)(dips * scale + 0.5f);
}

瞧!

关于Android - 在 LinearLayout 或 RelativeLayout 中为 View 的 topMargin/bottomMargin/等设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2239442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com