标签:des android c style class blog
05-29 21:23:28.406: E/AndroidRuntime(23636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.***.Main}:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child‘s parent first. 05-29 21:23:28.406: E/AndroidRuntime(23636): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
代码:
public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); if(dm.widthPixels>dm.heightPixels){ Fragment1 F1= new Fragment1(); getFragmentManager().beginTransaction().replace(R.id.MainID, F1).commit(); } else{ Fragment2 F2 = new Fragment2(); getFragmentManager().beginTransaction().replace(R.id.MainID, F2).commit(); } } }
public class Fragment2 extends Fragment {
public Fragment2(){
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.out.println("F2 onCreate");
}
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
System.out.println("F2 onCreateView");
return inflater.inflate(R.layout.fragment2, container,true);
}
}
错误的原因竟然是:return inflater.inflate(R.layout.fragment2, container,true)中的true;
修改成return inflater.inflate(R.layout.fragment2, container,false);
public View inflate (int resource, ViewGroup root, boolean attachToRoot) Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. 参数介绍: resource ID for an XML layout resource to load (e.g., R.layout.main_page) root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that
provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.) attachToRoot Whether the inflated hierarchy should be attached to the root parameter?
If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML. 返回值说明: The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root;
otherwise it is the root of the inflated XML file.
网络上面的解析:
1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2.
如果root不为null,attachToRoot设为true,则会在加载的布局文件的最外层再嵌套一层root布局。
3.
如果root不为null,attachToRoot设为false,则root参数失去作用。
4.
在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。
动态添加Fragment的报错信息,布布扣,bubuko.com
标签:des android c style class blog
原文地址:http://www.cnblogs.com/lyyh-victory/p/3760095.html