Fragment - 全局视图变量与本地和内部类侦听器以及内存泄漏 [英] Fragment - Global view variable vs local and inner class listeners and memory leak

查看:44
本文介绍了Fragment - 全局视图变量与本地和内部类侦听器以及内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设考虑以下两个不同的定义;

Suppose consider two different definitions below;

全局变量一;

View mainView;
ListView categoryList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater,  ViewGroup container,Bundle savedInstanceState) {
    mainView =  inflater.inflate(R.layout.fragment_expense_add,container,false);
    return mainView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    categoryList = (ListView) mainView.findViewById(R.id.categoryList);
    categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            catListAdapter.updateRadioButtons(position);
            if(amount.hasFocus())
                ((MainActivity)getActivity()).hideKeyboard();
        }
    });

本地

    Listview categoryList = (ListView) mainView.findViewById(R.id.categoryList);
    categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            catListAdapter.updateRadioButtons(position);
            if(amount.hasFocus())
                ((MainActivity)getActivity()).hideKeyboard();
        }
    });

哪个更能防止内存泄漏?

定义内部类触摸侦听器是否安全,如上所示,例如项目单击侦听器?当我的片段被销毁时,它是否仍然引用它?如何避免内存泄漏?

and is it safe to define inner class touch listeners as it is shown above such as item click listener? when my fragment is destroyed, does it keep still reference to it? How to avoid memory leak with this?

推荐答案

你的变量是局部变量还是成员变量没有区别.根据经验,如果您只需要特定方法中的变量,请将其设为该方法的本地变量(始终使用尽可能小的范围).

It makes no difference if your variable is local or a member variable. As a rule of thumb, if you only need the variable in a specific method, make it local to that method (always use the smallest scope you can).

内部类适用于小型方法,但对于较大的方法,请创建成员变量或类以保持代码简洁.

Inner classes are fine for small methods, but for larger ones create a member variable or a class to keep your code cleaner.

您上面显示的代码不会泄漏.

The code you show above does not leak.

这篇关于Fragment - 全局视图变量与本地和内部类侦听器以及内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆