32

如果我在 Fragment 中,我该如何调用父母的活动?

4

3 回答 3

81

是的,通过调用 getActivity 并将其与父活动一起转换以访问其方法或变量是正确的((ParentActivityName)getActivity())

试试这个。

ParentActivityName是父类名

于 2013-01-16T08:52:11.787 回答
17

2021 更新

正如评论中所说,Fragment#onAttach(Activity) 从 API 23 开始不推荐使用。反而:

@Override
public void onAttach(Context ctx) {
    super.onAttach(ctx);
    
    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        // Only attach if the caller context is actually an Activity
        if (ctx instanceof Activity) {
          mCallback = (OnHeadlineSelectedListener) ctx;
        }
    } catch (ClassCastException e) {
          throw new ClassCastException(ctx.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

原始答案

最合适的方法是让您Activity实现Interface和使用 listeners。这样,它就Fragment不会与任何特定的Activity保持它的可重复使用联系在一起。进入Fragment

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    
    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

这样,Activity当片段附加到片段时,您就会听到片段。

也可以看看:

于 2014-10-06T10:40:33.617 回答
0

只需使用 getActivity() 方法调用您的父活动。

CardView cardView = (CardView) getActivity().findView(R.id.your_view);
于 2017-12-05T11:20:38.740 回答