コメントで述べたようにonAttach
、フラグメントのメソッドを使用してこの問題を解決しましたが、この方法では、コールバック フィールド (この場合は mLogoutUser) をフラグメントで宣言し、次のように初期化する必要があります。
public class MyFragment extends ListFragment {
LogoutUser mLogoutUser;
// Container Activity must implement this interface
public interface LogoutUser {
public void logout();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mLogoutUser = (LogoutUser) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement LogoutUser");
}
}
...
}
詳細については、他のフラグメントとの通信を参照してください。
ただし、ケースがアクティビティで宣言されたフィールドである場合は、アクティビティのonAttachFragment
メソッドを使用して、リスナー フィールドを次のように初期化できます。
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
mLogoutUser = (LogoutUser) fragment;
}
また、イベント バスを使用して、フラグメントとアクティビティ間の通信を行うこともできます。オプションは、SquareのOtto ライブラリです。