gpt4 book ai didi

android - fragment 可以从其父 Activity 实现两个接口(interface)吗?

转载 作者:太空狗 更新时间:2023-10-29 16:37:36 26 4
gpt4 key购买 nike

为了在 fragment 之间进行通信,我们使用父 Activity 实现的接口(interface)模式...就像在文档中一样,例如 fragment 可以在其附加到 Activity 时获取父接口(interface)。

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}

@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 实现了另一个接口(interface)

public interface OnThreadCliked{
void onThreadClicked(Post post);
}

有没有办法获取对 Activity 实现的第二个接口(interface)的引用?

最佳答案

当然,只需施放两次:

OnThreadCliked mCallback2;

@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");
}

// This makes sure that the container activity has implemented
// the second callback interface. If not, it throws an exception
try {
mCallback2 = (OnThreadCliked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnThreadCliked");
}
}

关于android - fragment 可以从其父 Activity 实现两个接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857390/

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