有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

移动按钮安卓的java属性动画

我需要一个从左到右不断移动的按钮,每当我点击它,它就会做一些事情。我知道我需要使用属性动画来实现这一点。但我对它很迷茫。 这是我的主要观点。xml:

<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:paddingBottom="@dimen/activity_vertical_margin"
安卓:paddingLeft="@dimen/activity_horizontal_margin"
安卓:paddingRight="@dimen/activity_horizontal_margin"
安卓:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
    安卓:id="@+id/btn"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:layout_alignParentLeft="true"
    安卓:layout_alignParentTop="true"
    安卓:layout_marginLeft="39dp"
    安卓:layout_marginTop="106dp"
    安卓:text="Button" />

我如何编辑我的。java文件使用属性动画从左到右设置动画


共 (2) 个答案

  1. # 1 楼答案

    我会这样做:

    public class MyActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            //new GetUrl().execute(20);
    
            // Test XML Files
            //testXMLFiles();
    
            final Button speakButton = (Button)findViewById(R.id.play);
    
            speakButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    // TODO: DO something!
                }
            });
    
            final ObjectAnimator horizontalAnimator = ObjectAnimator.ofInt(new ButtonAnimatorHelper(speakButton), "marginLeft", 0, 600);
    
            horizontalAnimator.setDuration(2000);
            horizontalAnimator.setRepeatCount(ValueAnimator.INFINITE);
            horizontalAnimator.setRepeatMode(ValueAnimator.REVERSE);
            horizontalAnimator.setInterpolator(new LinearInterpolator());
    
            horizontalAnimator.start();
        }
    
        /**
         * Helper class for button animation
         */
        private static class ButtonAnimatorHelper {
    
            final Button mButton;
            /**
             * Default constructor
             * @param speakButton
             */
            public ButtonAnimatorHelper(final Button button) {
                mButton = button;
            }
    
            public void setMarginLeft(final int margin) {
                final ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mButton.getLayoutParams();
    
                params.leftMargin = margin;
    
                mButton.setLayoutParams(params);
            }
        }
    }
    

    为了更好地理解属性动画,我建议this session from Google I/O 2013,当然还有the tutorial here

  2. # 2 楼答案

    看看这个教程Android Animations

    设置布局动画的最简单方法是执行以下操作:

        your_layout.animate().translationX(your_layout.getWidth()).setDuration(500).setInterpolator(new AccelerateDecelerateInterpolator());