gpt4 book ai didi

android - 获取父布局的宽度

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

Android Studio 2.0 beta 6

我正在尝试使用 ViewPropertyAnimator 将 ImageView (ivSettings) 移动到工具栏内,使其距离右侧 20dp,距离顶部 20dp,即当前位置。并将 ImageView (ivSearch) 从左侧和顶部移动 20dp。

imageView 包含在 Toolbar 中。

这是初始状态,我想将图标移动到工具栏内的上角。

enter image description here

我使用的代码是这样获取宽度,然后减去一个值,使 ivSettings 距离右侧为 20dp。

final DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final float widthPx = displayMetrics.widthPixels;

ivSearch.animate()
.setInterpolator(new AccelerateInterpolator())
.x(20)
.y(20)
.setDuration(250)
.start();

ivSettings.animate()
.setInterpolator(new AccelerateInterpolator())
.x(widthPx - 160)
.y(20)
.setDuration(250)
.start();

但是,在不同的屏幕尺寸上尝试过后,我无法得到准确的宽度计算结果。有更好的方法吗?

非常感谢任何建议

最佳答案

您应该能够使用 translationXtranslationY 属性来实现您想要的效果。这些属性充当 View 原始 X 和 Y 坐标的偏移量。

本质上,translationX 会将 View 从其 X 坐标向右移动以获得正值,向左移动以获得负值。类似地,translationY 将 View 从其 Y 坐标移向底部以获得正值,将 View 移向顶部以获得负值。

关于您的问题,我假设您想要到达的最终位置是搜索图标的左上角,以及设置图标的右上角,每个 View 都使用零填充。

对于搜索图标,我建议您先将它放在工具栏的左上角。然后将 translationX 和 translationY 都设置为 20p。这应该将搜索图标放在与您的图像相同的位置。要将搜索图标移动到左上角,您只需将 translationX 和 Y 从 20dp 动画化到 0dp。

对设置图标重复相同的操作,但将 translationX 设置为 -20dp,将 translationY 设置为 20dp。这样它就会被放置在与您的图像相同的位置。将两个值设置为 0 以实现所需的动画效果。

这里是动画代码供引用。

ivSearch.animate()
.setInterpolator(new AccelerateInterpolator())
.translationX(0) // Takes value in pixels. From 20dp to 0dp
.translationY(0) // Takes value in pixels. From 20dp to 0dp
.setDuration(250)
.start();

ivSettings.animate()
.setInterpolator(new AccelerateInterpolator())
.translationX(0) // Takes value in pixels. From -20dp to 0dp
.translationY(0) // Takes value in pixels. From 20dp to 0dp
.setDuration(250)
.start();

// To get pixels from dp
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

这种方法的好处在于您不再需要知道父级的尺寸。您只关心您通过 translationXtranslationY 指定的偏移量。

关于android - 获取父布局的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872505/

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