Android - Animate a View's topMargin/bottomMargin/etc in LinearLayout or RelativeLayout

后端 未结 5 2170
被撕碎了的回忆
被撕碎了的回忆 2020-12-25 08:24

I am trying to create a menu that slides up from the bottom. It starts with the menu\'s view just visible at the bottom of the screen, and then clicking it causes it to sli

5条回答
  •  醉话见心
    2020-12-25 09:07

    I feel like this is a bit less of a hack. Basically, it's making your own animator. Below it's setup for only modifying topMargin in a RelativeLayout, but it wouldn't be hard to generalize it.

    import java.util.Calendar;
    
    import android.app.Activity;
    import android.util.Log;
    import android.view.View;
    import android.view.animation.Interpolator;
    import android.widget.RelativeLayout.LayoutParams;
    
    public class MarginAnimation extends Thread {
        final String TAG = "MarginAnimation";
        long mStartTime;
        long mTotalTime;
        Interpolator mI;
    
        int mStartMargin;
        int mEndMargin;
    
        View mV;
        Activity mA;
        public MarginAnimation(Activity a, View v, 
                int startMargin, int endMargin, int totaltime,
                Interpolator i) {
            mV = v;
            mStartMargin = startMargin;
            mEndMargin = endMargin;
            mTotalTime = totaltime;
            mI = i;
            mA = a;
        }
    
        @Override
        public void run() {
            mStartTime = Calendar.getInstance().getTimeInMillis();
            while(!this.isInterrupted() && 
                    Calendar.getInstance().getTimeInMillis() - mStartTime < mTotalTime) {
    
                mA.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(MarginAnimation.this.isInterrupted())
                            return;
                        long cur_time = Calendar.getInstance().getTimeInMillis();
                        float perc_done = 1.0f*(cur_time-mStartTime)/mTotalTime;
    
                        final int new_margin = (int)(1.0f*(mEndMargin-mStartMargin)*mI.getInterpolation(perc_done)) + mStartMargin;
                        LayoutParams p = (LayoutParams) mV.getLayoutParams();
                        Log.v(TAG, String.format("Setting Margin to %d", new_margin));
                        p.topMargin = new_margin;
                        mV.setLayoutParams(p);                  
                    }
                });
    
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    
    }
    

提交回复
热议问题