gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:44:32 26 4
gpt4 key购买 nike

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

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

我遇到的问题涉及从 DialogFragment 中按钮的 OnClickListener 方法中的 OnClick 方法调用 MyActivity 类中的函数。

它正在工作;我只是想明白为什么。

如果我尝试直接引用该函数 (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
}

最佳答案

 // 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 已在该对象上调用

总而言之 - 如果没有可以调用非静态方法的对象,则无法调用它们。

关于java - FragmentActivity 强制转换以避免静态引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11075422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com