我正在编写一个应用程序,MainActivity包含多个片段,我想最初隐藏一些片段,所以我做了这样的事情:
//Some class variables in MainActivity
private F1 f1 = new F1();
private F2 f2 = new F2();
private F3 f3 = new F3();
//some more variables...
//onCreate in MainActivity
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.container, f1);
ft.add(R.id.container, f2);
ft.hide(f2);
ft.add(R.id.container, f3);
ft.hide(f3);
ft.add(R.id.container, f4);
ft.add(R.id.container, f5);
ft.add(R.id.container, f6);
ft.commit();
//Methods in MainActivity
public void showf2(){
getFragmentManager().beginTransaction().show(f2).commit();
}
public void showf3(){
getFragmentManager().beginTransaction().show(f3).commit();
}
//F2
public class F2 extends Fragment{
private LinearLayout view;
private FrameLayout hContainer;
private LinearLayout list;
private TextView title;
private ScrollView scrollView;
private LinearLayout scrollViewInner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = new LinearLayout(getActivity());
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
));
hContainer = new FrameLayout(getActivity());
list = new LinearLayout(getActivity());
title = new TextView(getActivity());
scrollView = new ScrollView(getActivity());
scrollViewInner = new LinearLayout(getActivity());
//...
//some more code here
list.addView(title);
scrollView.addView(scrollViewInner);
list.addView(scrollView);
hContainer.addView(list);
view.addView(hContainer);
return view;
}
f2和f3的视图是动态创建的,这意味着视图是使用Java代码而不是XML生成的。我单独测试了布局,并且它们显示正确,因此您可以假设f2和f3中的代码是正确的。
showf2()和showf3()用于再次显示片段。 但是,当我调用这两种方法时,片段根本没有显示。但是如果我在片段中添加一些静态视图(使用XML),那么f2和f3中的静态视图可以通过调用showf2()和showf3()来显示。
那么,任何人都可以解释原因并发现问题吗?谢谢。