繁体   English   中英

如何创建动画类以在 android 中的其他活动中使用?

[英]How can I create an animation class to use in other activities in android?

我有这个用于下降图像的动画活动。 它完美地工作。 我想要改变这一点,所以我可以在另一个活动中调用类似 startImageFallAnimation() 的东西,并让它显示在当前活动上。 我不想将所有这些代码添加到我想在其中使用它的每个活动中。我试验了几个小时,但没有成功。

我怎样才能做到这一点?

import com.tmp.animation.R;

public class FallAnimationActivity extends Activity {

// 100 = lots falling / 1000 = less falling
public int imageInterval = 100;

private int[] LEAVES = { 
        R.drawable.coin,
        R.drawable.starsm,
        //R.drawable.leaf_yellow,
        //R.drawable.leaf_other,
    };

private Rect mDisplaySize = new Rect();

private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();

private float mScale;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Display display = getWindowManager().getDefaultDisplay(); 
    display.getRectSize(mDisplaySize);

    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    mScale = metrics.density;

    mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);

    new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}

public void create() {
    setContentView(R.layout.main);

    Display display = getWindowManager().getDefaultDisplay();
    display.getRectSize(mDisplaySize);

    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    mScale = metrics.density;

    mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);

    new Timer().schedule(new ExeTimerTask(), 0, imageInterval);
}


public void startAnimation(final ImageView aniView) {

    aniView.setPivotX(aniView.getWidth()/2);
    aniView.setPivotY(aniView.getHeight()/2);

    long delay = new Random().nextInt(Constants.MAX_DELAY);

    final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
    animator.setDuration(Constants.ANIM_DURATION);
    animator.setInterpolator(new AccelerateInterpolator());
    animator.setStartDelay(delay);

    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        int angle = 50 + (int)(Math.random() * 101);
        int movex = new Random().nextInt(mDisplaySize.right);

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float value = ((Float) (animation.getAnimatedValue())).floatValue();

            aniView.setRotation(angle*value);
            aniView.setTranslationX((movex-40)*value);
            aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
        }
    });

    animator.start();
}

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        int viewId = new Random().nextInt(LEAVES.length);
        Drawable d = getResources().getDrawable(LEAVES[viewId]);
        LayoutInflater inflate = LayoutInflater.from(FallAnimationActivity.this);
        ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
        imageView.setImageDrawable(d);
        mRootLayout.addView(imageView);

        mAllImageViews.add(imageView);          

        LayoutParams animationLayout = (LayoutParams) imageView.getLayoutParams();
        animationLayout.setMargins(0, (int)(-150*mScale), 0, 0);
        animationLayout.width = (int) (60*mScale);
        animationLayout.height = (int) (60*mScale);

        startAnimation(imageView);
    }
};

private class ExeTimerTask extends TimerTask {
    @Override
    public void run() {
        // we don't really use the message 'what' but we have to specify something.
        mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
    }
}
}

编辑 - 经过大量工作,这是我所拥有的最好的,但我无法解决将上下文传递到处理程序,或将布局传递到第一个方法的问题。

import com.tmp.animation.R;


public class FallPop {

private static final String TAG = FallPop.class.toString();

private static final FallPop INSTANCE = new FallPop();

private int[] LEAVES = {
        R.drawable.leaf_green,
        R.drawable.leaf_red,
        R.drawable.leaf_yellow,
        R.drawable.leaf_other,
};

private Rect mDisplaySize = new Rect();

private RelativeLayout mRootLayout;
private ArrayList<View> mAllImageViews = new ArrayList<View>();

private float mScale;


private FallPop(){

}

public static FallPop getInstance() {

    return INSTANCE;
}

public Context context;

public Context context2;

int count = 0;

public void doAnim(Context context){

    WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);

    Display display = wm.getDefaultDisplay();
    display.getRectSize(mDisplaySize);

    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    mScale = metrics.density;

    // FIX!!!
   // mRootLayout = (RelativeLayout) findViewById(R.id.main_layout);

    new Timer().schedule(new ExeTimerTask(), 0, 200);

}

public void startAnimation(final ImageView aniView) {

    aniView.setPivotX(aniView.getWidth()/2);
    aniView.setPivotY(aniView.getHeight()/2);

    long delay = new Random().nextInt(Constants.MAX_DELAY);

    final ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
    animator.setDuration(Constants.ANIM_DURATION);
    animator.setInterpolator(new AccelerateInterpolator());
    animator.setStartDelay(delay);

    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

        int angle = 50 + (int)(Math.random() * 101);
        int movex = new Random().nextInt(mDisplaySize.right);

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float value = ((Float) (animation.getAnimatedValue())).floatValue();

            aniView.setRotation(angle*value);
            aniView.setTranslationX((movex-40)*value);
            aniView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value);
        }
    });

    animator.start();
}



Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int viewId = new Random().nextInt(LEAVES.length);

            // Need some context here                 \/
            Drawable d = ContextCompat.getDrawable(context, LEAVES[viewId]);
            // Original line, also didnt work \/
            //Drawable d = getResources().getDrawable(LEAVES[viewId]);

            LayoutInflater inflate = LayoutInflater.from(context);
            ImageView imageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null);
            imageView.setImageDrawable(d);
            mRootLayout.addView(imageView);

            mAllImageViews.add(imageView);

            RelativeLayout.LayoutParams animationLayout = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
            animationLayout.setMargins(0, (int) (-150 * mScale), 0, 0);
            animationLayout.width = (int) (60 * mScale);
            animationLayout.height = (int) (60 * mScale);

            startAnimation(imageView);
        }
    };





class ExeTimerTask extends TimerTask {
    @Override
    public void run() {
        // we don't really use the message 'what' but we have to specify something.
        mHandler.sendEmptyMessage(Constants.EMPTY_MESSAGE_WHAT);
    }
}

}

我能想到的最快解决方案是让目标Activities扩展此类并将FallAnimationActivity成员变量的访问级别更改为“受保护”。 根据您是否需要在所有/大多数Activities ,我会将逻辑放在基类中。

创建一个带有静态方法 startImageFallAnimation() 的 Java 类,您将在其中编写所有动画代码,并在需要的地方调用该方法

将上下文作为您的 util 类中的参数

例子:

public animation(Imageview imageview, Context mContext)
{
Animation slideLeft = AnimationUtils.loadAnimation(mContext, R.anim.slide_out_left);
 imageview.startAnimation(slideLeft);
}

然后在你想要调用它的活动中做

// for activity
Utils.animation(Your image view, this)

//for fragment
Utils.animation(Your image view, getContext)

我的实用程序类称为 Utils,因此您可以输入您命名该类的任何内容并相应地调用该方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM