Is calling the method getActivity() once in my fragment and saving the reference in mActivity better than calling getActivity() every time I want to show a toast message?
Toast.makeText(mActivity, text, duration).show();
vs.
Toast.makeText(getActivity(), text, duration).show();
getActivity()
should be preferred for 2 reasons:
1) Memory leak prevention
Having a variable mActivity
lying around opens up opportunities for memory leak eg mistakenly set the variable as static , makes it easy and convenient to reference the activity in some running anonymous AysncTask
2) Correct nature of fragment-activity relationship
Fragments can be attached or detached at many point of times. Therefore, getting a reference of the activity hosting the current fragment should be on a on-demand basis . Having a mActivity
variable means you need to set and unset it correctly.
Take note that what Toast
requires here is a Context
object so it's not necessarily the activity that is required here. An application context object would also suffice
Fragment wise both are same
First one
Activity mActivity = getActivity();
@Override
public void onClick(View arg0) {
Toast.makeText(**mActivity**,"Text!",Toast.LENGTH_SHORT).show();
}
Second one
use Directly like this
Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
if you just need a Context or Activity, no difference. but if you want to access some method or field inside the parent activity, you would better saving the reference in mActivity.
如果您只想让上下文显示Toast
消息并且很难获得对Activity的引用,则可以使用getApplicationContext()
代替。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.