我有一项活动,其中包含4个奖励。在屏幕旋转时,活动崩溃,说明如下:
04-01 16:43:46.670: E/AndroidRuntime(2401): Caused by: java.lang.InstantiationException: can't instantiate class com.example.activity.FragmentActivity$UserFragment; no empty constructor
04-01 16:43:46.670: E/AndroidRuntime(2401): at java.lang.Class.newInstanceImpl(Native Method)
04-01 16:43:46.670: E/AndroidRuntime(2401): at java.lang.Class.newInstance(Class.java:1319)
04-01 16:43:46.670: E/AndroidRuntime(2401): at android.app.Fragment.instantiate(Fragment.java:574)
我已经看到了这个question,它说片段类必须声明为public。它被宣布为公开,并不能解决问题。
以下是我的代码:
public class FragmentActivity extends Activity
{
public class TabListener implements ActionBar.TabListener
{
private Fragment mFragment;
public TabListener(Fragment fragment)
{
mFragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft)
{
ft.add(R.id.fragmentContainer, mFragment, null);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{
ft.remove(mFragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft)
{
}
}
public class UserFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
.....
.....
}
}
@Override
public void onCreate(android.os.Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab userTab = actionBar.newTab();
userTab.setIcon(R.drawable.person).setTabListener(new TabListener(new UserFragment()));
actionBar.addTab(userTab);
}
}
答案 0 :(得分:3)
UserFragment必须是静态嵌套类才能重新实例化:
public static class UserFragment extends Fragment {
....
}
答案 1 :(得分:1)
您是否尝试将 android:launchMode =“singleTask”添加到AndroidManifest.xml。
示例:
<activity
android:launchMode="singleTask"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
答案 2 :(得分:1)
尝试为片段
创建一个空构造函数public class UserFragment extends Fragment {
public UserFragment(){}
....
}
答案 3 :(得分:1)
答案 4 :(得分:0)
1)向UserFragment类添加一个emty构造函数:
public class UserFragment extends Fragment
{
public UserFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
.....
.....
}
}
2)确保UserFragment类是一个单独的类(不在FragmentActivity类中)和单独的* .java文件(例如:UserFragment.java)
答案 5 :(得分:0)
看到你的代码看起来你已经在同一个类中定义了所有的片段,而只是为每个片段创建单独的类文件。
这对我来说是一种魅力