我创建了一个 fragment ,但找不到该 fragment 中接口(interface)类的用途...我用谷歌搜索但找不到正确的文档?
感谢您的关心!
public class SongListFragment extends Fragment {
public SongListFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
songIds = getArguments().getIntArray(SONG_IDS);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
//what's the use?
public interface OnFragmentInteractionListener {
public void onSongSelected(int songId);
}
}
最佳答案
OnFragmentInteractionListener
可用于 communicate fragment 之间
To allow a
Fragment
to communicate up to its Activity, you can define an interface in theFragment
class and implement it within the Activity. The Fragment captures the interface implementation during itsonAttach()
lifecycle method and can then call the Interface methods in order to communicate with the Activity.
查找另一个 SO 示例 here
关于android - fragment 中的接口(interface)类有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42211034/