布局右侧和底部的视图在移动时的行为与左侧和顶部的视图不同

Posted

技术标签:

【中文标题】布局右侧和底部的视图在移动时的行为与左侧和顶部的视图不同【英文标题】:Views right and bottom of layout behave differently than views on left and top when moving 【发布时间】:2021-10-06 20:53:51 【问题描述】:

我正在创建一个游戏应用程序,当我想创建介绍页面时,我有 4 个位图应该“进入”场景,每侧一个(上、左、右、下)。它们都以编程方式添加到场景中。

场景布局简单:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_>
    <RelativeLayout
        android:id="@+id/playground"
        android:layout_
        android:layout_
        android:clipChildren="false"
        android:clipToPadding="false"
        >
    </RelativeLayout>
</RelativeLayout>

我已经确定了游乐场视图大小(以像素为单位)并添加了 4 张图片。左应添加到视图的左侧,然后移动到原始位置。所有其他图像都一样,它们在视图之外,并且在视图内移动。

添加左图示例:

RelativeView playground = view.findViewById(R.id.playground);

/* some playground size calculations..., after ViewTreeObserver */
int playAreaWidth = playground.getWidth();
int playAreaHeight = playground.getHeight();

ImageView leftBack = new ImageView(requireContext());
leftBack.setScaleType(ImageView.ScaleType.FIT_XY);
leftBack.setImageResource(R.drawable.back_left);
playground.addView(leftBack);

/* some image size calculations... gettnig variables maxLeftWidth */
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(maxLeftWidth, playAreaHeight);
params.leftMargin = -maxLeftWidth;
params.topMargin = 0;
leftBack.setLayoutParams(params);

和一个简单的动画,将左图像从视图外部移动到 x 坐标 0

Animation a = new Animation() 
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) 
        RelativeLayout.LayoutParams paramsMoving = new RelativeLayout.LayoutParams(maxLeftWidth, playAreaHeight);
        paramsMoving.leftMargin = (int) (-maxLeftWidth + maxLeftWidth * interpolatedTime);
        paramsMoving.topMargin = 0;
        leftBack.setLayoutParams(paramsMoving);
    
;
a.setDuration(300);
leftBack.startAnimation(a);

并且按预期工作。顶部图像向下移动也是如此。

但是,问题在于底部和右侧图像。它们不是从视图外部移动到视图中,而是按比例缩放。看起来右图像的右边缘和底部图像的下边缘不能在视图之外。 x右图位置和y下图位置在动画过程中正确变化,但图像宽度(右图)和高度(下图)不正确。

有没有办法强制它在视图之外以适当的大小显示?

【问题讨论】:

不同的解决方案,但为什么不选择 ConstraintLayoutConstraintSet 用于动画,甚至更好的是 MotionLayout (Examples),专为动画设计。 【参考方案1】:

我在考虑ConstraintLayoutMotionLayout(就像Lalit Fauzdar 说的那样)但是,我仍然不熟悉它们,并且会有很多静态动画视图,所有动态添加,取决于游戏的进展情况开。

我找到的解决方案是使用FrameLayout 代替RelativeLayout(和FrameLayout.LayoutParams 代替RelativeLayout.LayoutParams),所有的工作都像一个魅力。

【讨论】:

以上是关于布局右侧和底部的视图在移动时的行为与左侧和顶部的视图不同的主要内容,如果未能解决你的问题,请参考以下文章

如何在表格视图单元格内的视图顶部和底部放置阴影?

使自定义单元格(使用自动布局创建)高度为零

使用导航栏和工具栏布局 TableView

PHP图像从顶部,底部,左侧和右侧裁剪

如何限制可拖动区域?它在顶部和左侧起作用,但在右侧和底部不起作用

如何以编程方式在顶部和底部的垂直线性布局中设置一个视图?