((ActivityName) getActivity()).FragmentName.methodInFragment(); - (ActivityName) 在做什么,它是如何工作的?

((ActivityName) getActivity()).FragmentName.methodInFragment(); - what is (ActivityName) doing and how does it work?

我这里有三个项目:一个名为 ActivityName 的基 activity,一个名为 FragmentName 的 activity 片段,以及一个 dialogFragment 从片段中调用。

我想从片段中的对话框中调用一个方法。我使用以下方法做到了这一点:

((ActivityName) getActivity()).fragmentName.methodInFragment();

我一直在尝试几种不同的解决方案,最后想到了这个。我明白发生了什么,但我不明白 (ActivityName) 在做什么。我的猜测是它将 getActivity 转换为实际的 activity 类型,因此我可以从它调用东西(比如我在其中声明的片段的实例)。那是正在发生的事情还是我离开了?

当我访问我在 XML 中定义的 TextView 时使用的是同一类型的东西吗?例如TextView myTextView = (TextView) findViewById(R.id.thetextview);?

这叫演员表。 getActivity() returns 一个 Activity 对象,并且使用 ((ActivityName)getActivity()) 指定 getActivity() 实际上是 class ActivityName 的对象.转换为特定类型允许您访问不属于超 class 的成员和方法 (public)。如果你定义了一个错误的转换,你会得到一个 ClassCastException.

Is this the same type of thing that's use when I am accessing a TextView I've defined in XML. e.g. TextView myTextView = (TextView) findViewById(R.id.thetextview);?

是的。 findViewByIdreturns一个View,你说View其实是一个TextView。如果 TextViewR.id.thetextview 不是 ImageButton 的 ID,则将其转换为 TextView 会导致 ClassCastException