FragmentActivity强制转换以避免静态引用

时间:2012-06-17 22:55:49

标签: java android casting static

我是Java和Android的初学者,我认为这更像是一个Java问题,因为它体现在Android中。

我正在使用Android支持包(android.support.v4.app)并在我的基类MyActivity中使用DialogFragment创建一个对话框,它扩展了FragmentActivity。

我遇到的问题是在OnogListener方法中使用OnClick方法调用MyActivity类中的函数来调用DialogFragment中的按钮。

它正在运作;我只想了解原因。

如果我尝试直接引用该函数(MyActivity.someFunction()),我得到“无法从MyActivity类型中对非静态方法someFunction()进行静态引用。”任何人都有一个很好的方法来解释静态与非静态以及为什么这个特定的引用是静态的?我认为这是因为DialogFragment被声明为静态。声明子类/方法静态与非静态的目的是什么。也就是说,为什么方法属于类而不是实例化对象?

此外,在此示例中,为什么以及如何绕过静态引用?

谢谢!

public static class myDialogFragment extends DialogFragment {
    static myDialogFragment newInstance(int whichDialog) {
        myDialogFragment f = new myDialogFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.invasive_edit_dialog, container, true);

        Button btn_apply_coords = (Button)v.findViewById(R.id.btn_get_coord);
        btn_apply_coords.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                    // This does not work ("Cannot make a static reference to the non-static method someFunction() from the type MyActivity").
                MyActivity.someFunction();


                    // This does not work ("The method someFunction() is undefined for the type FragmentActivity"). Eclipse suggests casting (a few lines down).
                getActivity().someFunction();

                    // This works; casted version of code above.  What is this code doing?
                ((MyActivity) getActivity()).someFunction();

                    // this works also
                MyActivity thisActivity =  (MyActivity) getActivity();
                thisActivity.someFunction();
            }
        });

        return v;
    }
}

public void someFunction() {
    // do something
}

1 个答案:

答案 0 :(得分:2)

 // This does not work ("Cannot make a static reference to the non-static method someFunction() from the type MyActivity").
            MyActivity.someFunction();

这不起作用,因为你试图从类(MyActivity)调用此方法,而不是从该类的对象调用(例如(MyActivity activity))

 // This works; casted version of code above.  What is this code doing?
            ((MyActivity) getActivity()).someFunction();

这确实有效,因为,正如我想的那样,方法getActivity()返回了对象,它被转换为MyActivity,然后在该对象上调用MyActivity的非静态方法

总结一下 - 如果没有可以调用它们的对象,就无法调用非静态方法。