我正在使用带有标签的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提供一个空构造函数没有帮助。我实际使用的片段称为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) {
}
}
ArticleListFragment.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;
}
}
为什么这段代码错了?
答案 0 :(得分:1)
MainActivity
的完整代码是什么?它并没有抱怨尝试实例化MainActivity
,而是$1
的匿名内部类(由MainActivity
表示)。