片段中的 UI 元素 ID 是否可以被父 activity 自动访问?

Are UI element ID's in a fragment automatically able to be accessed by the parent activity?

我似乎找不到任何用例,而且 Android 开发人员对此不太清楚。我得到它来访问片段中的活动 UI 元素,我需要调用 getActivity.findViewById,并从 Activity 其 getFragment.findFragmentById 中访问片段。但是对于 activity,如果 Fragments 附加到 activity,我可以只调用 findViewById 而不调用其他任何东西吗?本质上,Activity 是否自动知道包含的 Fragments UI 元素的视图 ID。

findViewById() 只是遍历布局以找到具有该 ID 的视图。当 Fragment 附加到 Activity 时,它会添加到 Activity 的布局中。所以是的,您可以通过 Activity 的 ID 访问 Fragment 的视图,但我强烈建议不要这样做。在 Fragment 上添加一个 public 方法,让您可以根据需要对这些视图进行任何更改。这样你就可以自由地改变你的布局而不用担心破坏主机 Activity

此外,您不需要在 Fragment 中使用 getActivity().findViewById() - 只需覆盖 onViewCreated(),然后在提供的 [=23= 上调用 findViewById() ] 实例。或者在 onCreateView()onDestroyView() 之间的生命周期中的任何时候,您可以使用 getView().findViewById().

例如:

public void onViewCreated(View view, Bundle savedInstanceState) {
    TextView fragmentTextView = (TextView) view.findViewById(R.id.textview_in_fragment);
}