【问题标题】:How to change TextView Text from static method?如何从静态方法更改 TextView 文本?
【发布时间】:2021-02-24 20:29:50
【问题描述】:

我的应用程序中有一个不断增加的值,执行此操作的处理程序位于我的“EventHandlerClass.java”内的静态方法中。 我现在想在 MainActivity 中的 TextView 上显示这个值。

这是我的处理程序的静态方法:

public static void pointsCounter() {
        handler = new Handler(Looper.getMainLooper());

        runnable = new Runnable() {
            public void run() {
                points = points + 5;
                String pointMsg = "Points: " + points;
                MainActivity.coinsTextView.setText(pointMsg);
                 
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }

这个 pointsCounter 方法是从 EventHandlerClass.java 中的另一个静态方法调用的。

它每秒增加点值 +5,我希望它显示在 TextView 中。 正确的方法是什么? 因为当我以这种方式尝试时,我必须将 MainActivity 中的 coinTextView 设为静态,我们都知道您不能从静态上下文中引用非静态变量。 当我这样做时,它告诉我“不要将 Android 上下文类放在静态字段中;这是内存泄漏”。 所以我的问题是如何从静态方法更新我的 UI 元素而不会有内存泄漏的风险? 正确的做法是什么?

【问题讨论】:

    标签: java android memory-leaks static


    【解决方案1】:

    正如你所说,永远不要在你的应用程序中放置静态视图或上下文,因为它会导致内存泄漏,但是如果你仍然想在你的应用程序中使用静态 TextView,你可以将 TextView 包装在 WeakReference 中:

    WeakReference:弱引用是指强度不足以将对象保留在内存中的引用。如果我们尝试确定对象是否被强引用并且恰好是通过 WeakReferences,则该对象将被垃圾回收。 这是一个如何使用它的示例:

    public class MainActivity extends AppCompatActivity {
        private static WeakReference<TextView> viewWeakReference;
        private static Handler handler;
        private static int points;
        private TextView textView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            
            textView = findViewById(R.id.textV);
            viewWeakReference = new WeakReference<>(textView);
            pointsCounter();
        }
    
    
        public static void pointsCounter() {
            handler = new Handler(Looper.getMainLooper());
    
            Runnable runnable = new Runnable() {
                public void run() {
                    points = points + 5;
                    String pointMsg = "Points: " + points;
                    viewWeakReference.get().setText(pointMsg);
                    handler.postDelayed(this, 1000);
                }
            };
            handler.postDelayed(runnable, 1000);
        }
    }
    

    【讨论】:

    • 正是我想要的,一种快速简单且安全的方法。谢谢!
    • 嗯,它很弱,不会泄漏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2012-05-28
    相关资源
    最近更新 更多