在使用Android Studio 使用默认创建Fragment时,在Activity中 must implement OnFragmentInteractionListener 错误如下:
Caused by: java.lang.ClassCastException: com.example.fengge.myapplication.MainActivity@534dfca8 must implement OnFragmentInteractionListener
此时Activity类如下:
public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
想要修改错误,只要Activity中实现定义的fragment的OnFragmentInteractionListener
修改后代码如下:
public class MainActivity extends FragmentActivity implements MyFragment.OnFragmentInteractionListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onFragmentInteraction(Uri uri) { } }
其中 MyFragment是我自己定义的fragment,只要改成自己创建fragment类名即可。