java - 当您不知道 View 的尺寸时如何移动 View ?

标签 java android android-animation

我想做的是在ImageView上对尺寸和位置的变化进行动画处理。为此,我使用以下方法:

void doAnimation() {
    ImageView logo = findViewById(R.id.logo);
    float scaleVal = R.attr.actionBarSize / logo.getHeight(); // Finds the scale needed to make the logo as tall as the actionBar

    // Gets the width and height in dp
    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    float density = getResources().getDisplayMetrics().density;
    float dpH = displayMetrics.heightPixels / density;
    float dpW = displayMetrics.widthPixels / density;

    // The final X and Y in dp
    float finalX = dpW - (logo.getWidth() / density) - 16;
    float finalY = dpH - (logo.getHeight() / density) - 16;

    // The final X and Y converted to %
    float finalXPercentage = finalX / dpW;
    float finalYPercentage = finalY / dpH;

    logo.animate()
        .setDuration(750)
        .scaleX(scaleVal)
        .scaleY(scaleVal)
        .translationX(finalXPercentage)
        .translationY(finalYPercentage);
}

我正在从 onResume() 方法调用 doAnimation() 方法,但由于显而易见的原因,我无法使用 getHeight()或在 onResume() 方法中使用 getWidth()

问题是我不知道 Logo 的高度或宽度,因为我使用的是 ConstraintLayout,因此我没有指定宽度或高度。我想做的是将 ImageView 移动到右上角(与其相距 16dp 的空间)并将其大小调整为与 ActionBar(工具栏)高度一样高。

最佳答案

您可以在 onLayoutChange 中尝试一下吗?我这样解决了我的问题。

logo.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) {
        mLayout.removeOnLayoutChangeListener(this);
        doyourAnimationcodehere();
    }
});

关于java - 当您不知道 View 的尺寸时如何移动 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49733597/

相关文章:

java - Ehcache 复制缓存 RMI Bootstrap

android - 如何在某些 Activity 中而不是在 fragment 中禁用返回

使 ImageView 运行的 Android 缩放动画

android - 取消动画,停止 applyTransformation 运行

javascript - 在 java 中安全运行 javascript 代码

java - 将插件从 1.6 升级到 1.7

java - 将数据从 Android 应用程序保存到远程服务器

安卓工作室错误 : Cannot load project

android - 动画运行时 OnClick 不起作用

java - android中recyclerview的分页