【问题标题】:How to share object for all app's activities如何为所有应用程序的活动共享对象
【发布时间】:2021-03-05 12:21:33
【问题描述】:

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

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

【问题讨论】:

    标签: java android singleton android-animation android-button


    【解决方案1】:

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

    例如:

    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" />
    

    【讨论】:

    • 很高兴为您提供帮助。如果是,请给予支持并将问题标记为已解决。编码愉快。
    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2011-03-15
    • 2012-04-15
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多