如果我在Fragment内部,如何调用父Activity?
如果我在Fragment内部,如何调用父Activity?
是的,通过调用getActivity并将其与父活动进行强制类型转换以访问其方法或变量是正确的 ((ParentActivityName)getActivity())
可以尝试这个。
ParentActivityName
是父类名称
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
并使用监听器。这样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
监听该片段。另请参阅:
onAttach(Activity activity)
已被弃用,请使用onAttach(Context context)
代替。 - Yohanim只需使用 getActivity() 方法调用您的父 Activity。
CardView cardView = (CardView) getActivity().findView(R.id.your_view);