[android] must implement OnFragmentInteractionListenerエラー
must implement OnFragmentInteractionListenerエラー
recyclerViewでItemのタップ処理を実装すると
must implement OnFragmentInteractionListenerエラー
もしくは
must implement OnListFragmentInteractionListenerエラー
がでることがある
こちらは
fragmentの
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
が反応しているためである
要は親のこのFragmentを呼び出している親ActivityにOnListFragmentInteractionListenerを継承していないことが理由
なのでActivityにOnListFragmentInteractionListenerを継承してあげれば良い
親Activity
public class MainActivity extends AppCompatActivity implements ItemFragment.OnListFragmentInteractionListener {
・・・
}
*ItemFragmentというFragmentにOnListFragmentInteractionListenerというinterfaceが実装されている必要がある
またinterfaceを継承した時に「関数が書かれていない」みたいなエラーが表示される場合は、継承したInterfaceが持っている関数をActivityにoverRideしていないので、ちゃんとInterfaceが持っている関数をすべてoverRideすること
親Activity
public class MainActivity extends AppCompatActivity implements ItemFragment.OnListFragmentInteractionListener {
//onListFragmentInteraction interfaceの関数「onListFragmentInteraction」をoverRide
@Override
public void onListFragmentInteraction(DummyContent.Dummy uri){
//you can leave it empty
switch (uri.id){
case "0":
//処理
break;
case "1":
//処理
break;
default:
}
}
}