Android实现静态或非静态片段接口

时间:2013-11-05 13:47:22

标签: java android android-fragments

假设我有这个片段:

public class FragmentA extends Fragment {

    public interface CallerProxy {
        public void publishParams(Object... dataParams);
    }

    private CallerProxy mCallerProxy;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof CallerProxy) {
            this.mCallerProxy = (CallerProxy) activity;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.mCallerProxy = null;
    }

    protected void sendCustomMessage(Object... objects) {
        if (mCallerProxy != null) {
            mCallerProxy.publishParams(objects);
        }
    }

}

将接口定义为静态还是非静态有什么区别?即使我声明CallerProxy静态,然后在父活动中,我也会这样:

public class MyProxyActivity extends FragmentActivity implements CallerProxy {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(...) and other relevant code
    }

    @Override
    public void publishParams(Object... dataParams) {
        // /
    }
}

据我所知,如果接口被声明为static,那么接口被绑定到FragmentA类对象,如果我没有声明它是静态的,那么它将绑定到FragmentA实例对象 - 这会导致内存泄漏吗?

如果界面不是静态的,可能会出现什么问题?为什么?

1 个答案:

答案 0 :(得分:1)

定义为类成员的interface已经(隐式)声明为static,因此您提到的两种方案之间没有任何差异。另外,作为参考,来自Java language specifications

的引用

Member interfaces (§8.5) are implicitly static so they are never considered to be inner classes.