我正在使用带有标签的 SherlockFragmentActivity。它第一次加载很好,但是当方向改变时,会出现以下错误:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{ext.domain.app/ext.domain.app.MainActivity}:
android.support.v4.app.Fragment$InstantiationException: Unable to instantiate
fragment ext.domain.app.MainActivity$1: make sure class name exists, is public,
and has an empty constructor that is public
我一直在查看有关类似问题的帖子,但有一点不同:在此错误中,似乎 MainActivity 被视为片段(“无法实例化片段 ext.domain.MainActivity”),而不是使用的片段类提及。
给 MainActivity 一个空的构造函数没有帮助。我实际使用的 Fragments 称为 ArticleListFragment,它是一个带有空构造函数的公共类。
我在 Android 2.3 上运行应用程序,下面是代码(去掉了最不相关的细节,仍然抛出异常):
MainActivity.java:
(编辑:添加了 ArticleListFragment 的实例化,它是一个匿名内部类型。似乎如果我删除它,它确实有效。)
public class MainActivity extends SherlockFragmentActivity implements ActionBar.TabListener {
ActionBar actionBar;
public MainActivity() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Create ActionBar
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create Tabs
String[] tabs = {
getString(R.string.tab1),
getString(R.string.tab2),
getString(R.string.tab3),
getString(R.string.tab4)
};
for(String tabname : tabs) {
ActionBar.Tab tab = actionBar.newTab();
tab.setText(tabname);
tab.setTabListener(this);
actionBar.addTab(tab);
}
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getPosition()) {
case 0:
ArticleListFragment home = new ArticleListFragment() {
public void onAttach(Activity activity) {
// This is some code to populate the Fragment with an HTTPRequest
super.onAttach(activity);
RequestParams paramsHome = RequestClient.getBasicRequestParams(activity);
populate("frontpage", paramsHome);
};
};
ft.replace(R.id.contentframe, home);
break;
case 3:
ArticleListFragment saved = new ArticleListFragment() {
public void onAttach(Activity activity) {
// This is some code to populate the Fragment with an HTTPRequest
super.onAttach(activity);
RequestParams paramsSaved = RequestClient.getBasicRequestParams(activity);
populate("saved", paramsSaved);
};
};
ft.replace(R.id.contentframe, saved);
break;
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
文章列表片段.java:
public class ArticleListFragment extends SherlockFragment {
public ArticleListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_articlelist, null);
return layout;
}
}
任何想法为什么这段代码是错误的?