能否请你告诉我什么是最好的做法是通过活动
或上下文
其他实例(;)
Can you please tell me whats the best practice to pass activity
or context
to other instance(;)
不过...
什么是更好的通过?活动
或上下文
是有活动好主意
作为全球(公共静态活动活动)
What is better to pass? Activity
or Context
Is good idea to have the Activity
as Global (public static Activity activity)
这里是我的code。你会怎样改变? (基于Android的好做法)
here is my code. What would you change? (based on good android practices)
传递一个活动
成没有特别要求的活动对象通常是一个坏主意。
活动
扩展上下文
所以它的工作原理,以满足需要的方法上下文
。
Passing an Activity
into another object that does not specifically require the Activity
object is usually a bad idea. Activity
extends Context
so it works to satisfy a method that requires Context
.
在你的情况,你可以得到上下文
从查看
传递到方法。但是,如果你需要的上下文
用于其它目的,你应该避免将活动
,并完成类似 Activity.getApplicationContext()
。
In your case, you can get the Context
from the View
that is passed into the method. However, if you need the Context
for other purposes, you should avoid passing Activity
and do something like Activity.getApplicationContext()
.
这样做的理由是,如果对象,你传递一个活动
进入生活比活动
,参考较长到活动
将prevent的Android从做适当的垃圾收集( GC
),消耗不必要的内存。这就是所谓的内存泄漏
The reason for this is if the object you pass an Activity
into lives longer than the Activity
, the reference to the Activity
will prevent Android from doing proper Garbage Collection (GC
) and consume unnecessary memory. This is called a "memory leak".
编辑:
要处理,你需要调用的情况 Activity.findViewById()
对这些事情记在心里。首先,这是一个查看
办法(的 http://developer.android.com/reference/android/view/View.html#findViewById(INT)),所以一定要从正确的观点来调用它。
To handle situations where you need to call Activity.findViewById()
keep these things in mind. First, that is a View
method (http://developer.android.com/reference/android/view/View.html#findViewById(int)) so be sure to call it from the correct view.
第二,如果你需要一个查看
从活动
你应该通过它作为一个的WeakReference
Second, if you need a View
from an Activity
you should pass it in as a WeakReference
上一篇:Android的 - 检测事件后的“X”号绕局部Z轴辊局部、事件、Android、轴辊
下一篇:ClassCast Expcetion在酒吧焦炭使用MPAndroidChart罐焦炭、酒吧、ClassCast、Expcetion