新建的一個Fragment,被一個Activity使用,那麼這個Activity須要繼承一個接口:java
public class MainActivity extends Activity implements HistoryFragment.OnFragmentInteractionListener{ }
不然會被報錯android
java.lang.ClassCastException: com.livingspring.luchebao.MainActivity@4261c220 must implement OnFragmentInteractionListener
at com.livingspring.luchebao.HistoryFragment.onAttach(HistoryFragment.java:84)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)spring
在新建的Fragment裏面有這樣一個複寫的方法app
@Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } }
明確要求 與之匹配的Activity須要繼承一個方法來進行通訊,繼承之後還要複寫一個方法:ide
@Override public void onFragmentInteraction(Uri uri) { }