Android - 仅在父视图上播放动画

时间:2014-03-27 03:23:00

标签: android animation view rotation

如何让动画仅在父视图上运行,让子视图保持原样(即没有设置动画)?

这是我的尝试:

public class TurnButton extends RelativeLayout implements OnClickListener, AnimationListener{

    private static final String TAG = TurnButton.class.getSimpleName();

    private final int textViewID = 1;

    public TurnButton(final Context context, final AttributeSet attrs, final int defStyle) {

        super(context, attrs, defStyle);
        setEverything();
    }

    public TurnButton(final Context context, final AttributeSet attrs) {

        super(context, attrs);
        setEverything();
    }

    public TurnButton(final Context context) {

        super(context);
        setEverything();
    }

    private void setEverything(){

        setOnClickListener(this);

        final TextView textViewNumber = new TextView(ThisApplication.getContext());
        textViewNumber.setId(textViewID);
        textViewNumber.setText("30");
        textViewNumber.setTextColor( ThisApplication.getContext().getResources().getColor(R.color.white) );

        final RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        relativeParams.addRule(RelativeLayout.CENTER_IN_PARENT);

        addView(textViewNumber, relativeParams);
    }

    @Override
    public void onClick(final View view) {

        final RotateAnimation rotate = new RotateAnimation( view.getRotation(), view.getRotation() - 360.0f, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                                                            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotate.setDuration(300);
        rotate.setFillEnabled(true);
        rotate.setFillAfter(true);
        view.startAnimation(rotate);

        view.findViewById(textViewID).setRotation(0);
    }
}

我想旋转TurnButton视图而不旋转TextView 我在其中心添加。

1 个答案:

答案 0 :(得分:2)

可以通过对子视图(TextView)应用反向旋转来实现:

@Override
public void onClick(final View view) {

    final RotateAnimation rotate = new RotateAnimation(view.getRotation(),
            view.getRotation() - 360.0f, RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    rotate.setDuration(300);
    rotate.setFillEnabled(true);
    rotate.setFillAfter(true);
    view.startAnimation(rotate);

    final TextView textView = (TextView)view.findViewById(textViewID);
    final RotateAnimation reverseRotate = new RotateAnimation(view.getRotation(),
            360.0f - view.getRotation(), RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);
    reverseRotate.setDuration(300);
    reverseRotate.setFillEnabled(true);
    reverseRotate.setFillAfter(true);
    textView.startAnimation(reverseRotate);
}