【发布时间】:2018-11-01 16:29:02
【问题描述】:
我有一个以编程方式创建片段的活动。 该片段内部还有另一个片段。
活动包含片段 A。 片段 A 包含片段 B。
一切都很完美, 除非我改变屏幕的方向。
当屏幕方向改变时,片段被复制。
我在网上(也在这里)寻找我的问题的解决方案, 我介绍了官方的android文档, 我试着做我的测试: 但我还没有回来寻找解决方案!
我看到其他人已经通过将创建片段的代码放在这个 if 中来解决:
if (savedInstanceState == null) {
}
但它对我不起作用!
如果我将创建片段的代码放在那个片段中,则不会创建片段。
我试图通过调试来确保活动的生命周期。
当应用第一次创建activity时:
- 活动
- 片段,附加
- 片段,oncreate
- 片段,oncreateview
当我水平转动屏幕时,应用程序通过这里:
- 片段,附加
- 片段,oncreate
- 活动
- 片段,oncreateview
- 片段,附加
- 片段,oncreate
- 片段,oncreateview
活动:
public class Activity extends AppCompatActivity {
ScrollView sv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
sv = findViewById(R.id.sv);
LinearLayout ll_fragment = new LinearLayout(this);
ll_fragment.setId(100);
ll_fragment.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
ll_fragment.setLayoutParams(LLParams);
ll.addView(ll_fragment);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ArrayList<Integer> AL_Int = new ArrayList<Integer>();
AL_Int.add(sv.getId());
fragment = FragmentA.newInstance(AL_Int);
fragmentTransaction.add(ll_fragment.getId(), fragment);
fragmentTransaction.commit();
}
片段:
public class FragmentA extends Fragment {
public static FragmentA newInstance(ArrayList<Integer> AL_Int_sv_ID) {
FragmentA f = new FragmentA();
Bundle b = new Bundle();
if(AL_Int_sv_ID.get(0) != null){
b.putInt("int_sv_ID", AL_Int_sv_ID.get(0));
b.putBoolean("bool_sv", true);
}else{
b.putInt("int_sv_ID", -1);
b.putBoolean("bool_sv", false);
}
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
int int_ScrollView_ID = args.getInt("int_sv_ID");
boolean bool_ScrollView = args.getBoolean("bool_sv");
bool_sv = bool_ScrollView;
int_sv_ID = int_ScrollView_ID;
if(bool_sv){
sv = getActivity().findViewById(int_ScrollView_ID);
sv = FA.findViewById(int_ScrollView_ID);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout ll = new LinearLayout(getActivity());
ll.setOrientation(LinearLayout.VERTICAL);
LLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
ll.setLayoutParams(LLParams);
ll.setId(20);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
FragmentB fragmentB = new FragmentB();
transaction.add(20, fragmentB);
transaction.commit();
return ll;
}
【问题讨论】: