我试图为我的DialogFragment实现一个onCompleteListener。但是在将片段附加到activity时会出错。如果我遗漏了
public void onAttach(Activity activity) {
try {
this.mListener = (OnCompleteListener) activity;
} catch (final ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnCompleteListener");
}
}
方法,对话框显示但是值没有传递回调用活动。我也为Activity实现了OnCompleteListener。 这是我在调用活动中的实现
public class ViewMoreActivity extends FragmentActivity implements
OnClickListener, BuySharesDialogFragment.OnCompleteListener {
-------------------------------
-------------------------------
@Override
public void onComplete(String shares, String total_cost, String sharename,
String paymentmode) {
Toast.makeText(getApplicationContext(), shares, Toast.LENGTH_LONG)
.show();
}
}
我的DialogFragment
public class BuySharesDialogFragment extends DialogFragment implements
OnClickListener, OnItemSelectedListener {
public static interface OnCompleteListener {
public abstract void onComplete(String shares, String total_cost,
String sharename, String paymentmode);
}
private OnCompleteListener mListener;
-------------------------------
-------------------------------
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_cancel:
getDialog().dismiss();
break;
case R.id.dialogbutton_buy_shares:
this.mListener.onComplete(String.valueOf(shares), total_cost
.getText().toString(), company_name.getText().toString(),
paymentmethod);
break;
}
}
public void onAttach(Activity activity) {
try {
this.mListener = (OnCompleteListener) activity;
} catch (final ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnCompleteListener");
}
}
我可能在哪里出错?堆栈跟踪错误指向onAttach()方法。 这是前几行
10-03 12:38:26.890: E/AndroidRuntime(5903): FATAL EXCEPTION: main
10-03 12:38:26.890: E/AndroidRuntime(5903): android.support.v4.app.SuperNotCalledException: Fragment BuySharesDialogFragment{405a5e38 #2 fragment_edit_name} did not call through to super.onAttach()
`10-03 12:38:26.890`: E/AndroidRuntime(5903): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:869)
10-03 12:38:26.890: E/AndroidRuntime(5903): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
答案 0 :(得分:1)
应该是
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
this.mListener = (OnCompleteListener) activity;
} catch (final ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
}
}
您忘了拨打super.onAttach(activity);
答案 1 :(得分:0)
执行此更改
public void onAttach(Activity activity) {
super.onAttach(activity); //UPDATE HERE
try {
this.mListener = (OnCompleteListener) activity;
} catch (final ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnCompleteListener");
}
}