android - fragment 中的接口(interface)类有什么用?

标签 android android-studio android-fragments

我创建了一个 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 the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() 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/

相关文章:

android - 如何在 RecyclerView.Adapter 中使用共享首选项?

java - 如何使用 css Selector Appium java 运行自动化测试

android - 将一个 fragment 滑过另一个 fragment

Android Firestore : Failed to gain exclusive lock to the Firestore client's offline persistence

android - 无法在 Windows 8.1 上安装 Android 的 OEM 驱动程序

java - 错误: on a null object reference, SavedInstanceState旋转回收器 View

android - 滑动tabs的时候,fragment的oncreateView没有被调用,怎么每次都调用oncreateView

java - 在android中解析Json对象?

android - 居中纹理 LibGDX

android - 错误:无法解决:com.esri.arcgis.android:arcgis-android:10.2.6-2