我在片段中创建了一个接口,如下所示:
public interface SGFCallBackInterface {
void itemSelected(Item item);
}
private SGFCallBackInterface mCallbackInterface;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SGFCallBackInterface) {
mCallbackInterface = (SGFCallBackInterface) context;
} else {
throw new RuntimeException(context.toString() + " must implement SelectGdsFragment.SGFCallBackInterface");
}
}
public void setSGFCallBackInterface(SGFCallBackInterface mCallbackInterface) {
this.mCallbackInterface = mCallbackInterface;
}
我将在另一个片段中实现,如下所示
public class SaleMenageFragment extends Fragment implements SelectGdsFragment.SGFCallBackInterface {
...
SelectGdsFragment selectGdsFragment = new SelectGdsFragment();
selectGdsFragment.setSGFCallBackInterface(SaleMenageFragment.this);
...
}
@Override
public void onItemSelected(Item item) {
...
}
但它仍然无效,这是错误日志:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.leo.test, PID: 3853
java.lang.RuntimeException: com.leo.test.Control.IndexActivity@2a66aece must implement SelectGdsFragment.SGFCallBackInterface
at com.leo.test.Control.Fragment.SaleManagement.SelectGdsClsFragment.onAttach(SelectGdsFragment.java:42)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
at android.support.v4.app.BackStackRecord.setLastIn(BackStackRecord.java:779)
at android.support.v4.app.BackStackRecord.calculateFragments(BackStackRecord.java:819)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:660)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
我认为错误日志意味着我的IndexActivity没有实现SelectGdsFragment.SGFCallBackInterface。
但我不想在IndexActivity中实现它 我想在SaleMenageFragment中实现它。
我该怎么做?
答案 0 :(得分:0)
只需删除onAttach(Context context)方法中的部分,如下所示:
public interface SGFCallBackInterface {
void itemSelected(Item item);
}
private SGFCallBackInterface mCallbackInterface;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SGFCallBackInterface) {
mCallbackInterface = (SGFCallBackInterface) context;
} // this wont throw an exception if the activity does not implement that interface
}
public void setSGFCallBackInterface(SGFCallBackInterface mCallbackInterface) {
this.mCallbackInterface = mCallbackInterface;
}
答案 1 :(得分:0)