【问题标题】:ViewPropertyAnimator messing with view layout positionViewPropertyAnimator 弄乱了视图布局位置
【发布时间】:2018-04-19 19:34:45
【问题描述】:

我创建了一个按钮,使用顶部和左侧边距设置位置并添加到布局中。如果我只是这样做,按钮就在正确的位置。

现在我需要添加一个翻译动画,我使用的是viewPropertyAnimator。 不幸的是,这会使初始按钮位置无效,使动画从 (0, 0) 开始。

以下是我写的代码。

        final Button bonus_button = new Button(this);

        int bonus_y_start, bonus_x_start, bonus_y_end, bonus_x_end;

        bonus_x_start = random.nextInt(2) == 1 ? layout_width + button_size : -1 * button_size;
        bonus_y_start = random.nextInt(layout_height + 2 * button_size) - button_size;

        if (bonus_x_start < 0) 
            bonus_x_end = layout_width + button_size;
        else
            bonus_x_end = -1 * button_size;

        bonus_y_end = random.nextInt(layout_height + button_size) - button_size;

        RelativeLayout.LayoutParams bonus_l = new RelativeLayout.LayoutParams(button_size, button_size);
        bonus_l.leftMargin = bonus_x_start;
        bonus_l.topMargin = bonus_y_start;
        bonus_button.setLayoutParams(bonus_l);

        bonus_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mHandler.sendEmptyMessage(MSG_PAUSE_TIMER);
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessage(MSG_RESUME_TIMER);
                    }
                }, 2000);
            }
        });

        bonus_button.bringToFront();

        ViewPropertyAnimator animator = bonus_button.animate().x(bonus_x_end).y(bonus_y_end);
        animator.setDuration(2000);
        animator.withEndAction(new Runnable() {
            @Override
            public void run() {
                layout.removeView(bonus_button);
            }
        });

        layout.addView(bonus_button);

有人知道我哪里做错了吗?

【问题讨论】:

    标签: android animation layout viewpropertyanimator


    【解决方案1】:

    使用bonus_l.setX(bonus_x_start)bonus_l.setY(bonus_x_start) 代替边距

    【讨论】:

    • 这很有效,谢谢。你能解释一下为什么吗?从编码的角度来看,两者都做同样的事情。
    猜你喜欢
    • 2021-11-22
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    相关资源
    最近更新 更多