如何为所有应用程序的活动共享对象

How to share object for all app's activities

我有一个动画,我想在我的应用程序中的每个按钮上应用它。所以我不想在每个 activity onCreate 方法中调用 AnimationUtils.loadAnimation() 。我只想在启动应用程序时调用此方法一次以初始化我的动画对象,然后在我的不同活动中获取它(使用 getter)。 我是 Android 编程的新手,我打算使用单例模式,但在与本文和其他 Whosebug 页面相关的 Android 中看起来“不安全”。 (https://programmerr47.medium.com/singletons-in-android-63ddf972a7e7)

是否可以在应用程序启动时创建我的动画并在每个 activity 之间共享?值得做一些优化吗?

我建议扩展 android Button/AppCompatButton class,将您想要的功能添加到扩展的 class 并使用该按钮在你的应用程序中的任何地方都更容易,而且可能是最正确的方式,

例如:

AnimatedButton.java:

package com.example.myapplication;

import android.content.Context;
import android.util.AttributeSet;

public class AnimatedButton extends androidx.appcompat.widget.AppCompatButton {
    public AnimatedButton(Context context) {
        super(context);
        createAnimation();
    }

    public AnimatedButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AnimatedButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void createAnimation() {
        // here create the animation and call
        // setAnimation([YOUR_ANIMATION_HERE]);
        // now you can simply call customButton.animate();
        // from anywhere in the code that uses the button and it should work
    }
}

在您要使用按钮的 xml 中:

<com.example.myapplication.AnimatedButton
            android:id="@+id/btn_animate"
            android:layout_width="180dp"
            android:layout_height="80dp"
            android:text="Animate" />