我仍然没有 100% 理解上下文、活动、片段等的概念/差异,所以请耐心等待。
在 SherlockFragment 中调用 getActivity() 时出现 ClassCastException(注意:我也尝试过 getSherlockActivity() 无济于事):
public abstract class TaskGrabbingFragment extends SherlockFragment {
...
protected void transferGroupToMe() {
...
Backend.getInstance().modifyTask(new OnModifyTaskResponse() {
@Override
public void onModifyTask(Map<String, Object> response) {
refresh();
}
}, (MyActivity) getActivity(), //ClassCastException
TaskHelper.TASK_IDS, ids,
TaskHelper.EMPLOYEE_ID, DomaCareBackend.getInstance().getUserId());
}
}
我的 logcat 输出:
FATAL EXCEPTION: main
java.lang.ClassCastException: com.mycom.task.AllTasksActivity cannot be cast to com.mycom.myapp.MyActivity
at com.mycom.myapp.task.TaskGrabbingFragment.transferGroupToMe(TaskGrabbingFragment.java:69)
at com.mycom.myapp.task.TaskGrabbingFragment.onContextItemSelected(TaskGrabbingFragment.java:47)
at android.support.v4.app.Fragment.performContextItemSelected(Fragment.java:1583)
at android.support.v4.app.FragmentManagerImpl.dispatchContextItemSelected(FragmentManager.java:1992)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:370)
at com.actionbarsherlock.app.SherlockFragmentActivity.onMenuItemSelected(SherlockFragmentActivity.java:211)
MyActivity扩展了SherlockFragmentActivity,异常发生在TaskGrabbingFragment,但是getActivity()返回AllTasksTabFragment,是一个SherlockFragment。那么是否有一些规则反对将 SherlockFragment 转换为 SherlockFragmentActivity?有什么样的解决方案可以将片段转换为片段活动?