Is it a good idea to declare static view in android?

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-10 19:54:50

问题


The problem : I have one class and one activity: The class do the logic and use a complex algorithms that manipulate Textview and ImageView from the activity What I'm doing :

In activity : static TextView txt1, txt2, txt3, txt4; so I can use in the class : Activity.txt1

Is it something bad in Android programming ? I wanted to learn best practise. So if you have a better method I would take it. Thanks


回答1:


I can't see any reason you'd ever want to do that. Static variables are shared between all instances of a class. But views are very much bound to their particular instance of Activity, they cannot be used by multiple instances- each instance must create their own. A View created by one instance of an Activity cannot be displayed in a second instance. So I can't see any case where a static View is a benefit.




回答2:


Declaring static views is a bad practice especially in your scenario wherein you declare it inside an activity. If your application grows, you might encounter memory problem exception that will result to application crashing because static views that you declare cannot be collected by the garbage collector in order to free up memory heap.




回答3:


Declaring views as static is not suggested for few reasons :

  1. It would lead to memory leak
  2. Static view referenced in one instance won't be available to the other instance
  3. View should only be referenced when the activity is created. Having a static view means we can assign it a reference even before activity is created which leads to problem.

In your case u can return the manipulated text or the new image and display the text or the image from the activity.



来源:https://stackoverflow.com/questions/34107165/is-it-a-good-idea-to-declare-static-view-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!