【发布时间】:2015-05-24 12:53:29
【问题描述】:
我的片段被创建了两次,即使活动只是将片段添加到内容中一次。当我旋转屏幕时会发生这种情况。此外,每次调用片段的 onCreateView 时,它都会丢失所有的变量状态。
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) { // Checking for recreation
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new AppPanelFragment())
.commit();
}
}
}
onCreate 在活动中检查 null savedInstanceState 并且只有 null 才会添加片段,所以我看不出为什么片段应该被创建两次?在 if 条件中放置一个断点告诉我它只会被调用一次,因此活动不应该多次添加片段。然而,每次方向改变时仍会调用片段的 onCreateView。
public class AppPanelFragment extends Fragment {
private TextView appNameText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This method called several times
View rootView = inflater.inflate(R.layout.fragment_app_panel, container, false);
// 2nd call on this method, appNameText is null, why?
appNameText = (TextView) rootView.findViewById(R.id.app_name);
appNameText.text = "My new App";
return view;
}
我设法使用 setRetainInstance(true) 保持变量状态,但这是真正的解决方案吗?我希望片段不会仅在方向更改时创建。
【问题讨论】:
标签: android android-activity fragment