The specified child already has a parent. You must call removeView() on the child's parent first.问解决

在学习Android Fragments时遇到一个运行时错误:The specified child already has a parent. 解决方案是,不要在inflate时为Fragment指定container,改为使用inflater.inflate(R.layout.fragment2, null)来避免给它指定父控件。" 116418084,10295491,Oracle密码重用限制参数详解,"['数据库管理', 'Oracle配置', '数据库安全']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天学习android fragments时,遇到一个运行时错误

The specified child already has a parent. You must call removeView() on the child's parent first.

源码如下:MainActivity.java  目的是根据屏幕尺寸的变化加载不同的fragment


public class MainActivity extends Activity {

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Display display = getWindowManager().getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);
		if(outMetrics.widthPixels > outMetrics.heightPixels){
			Fragment1 fragment1 = new Fragment1();
			
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
		}else{
			Fragment2 fragment2 = new Fragment2();
			getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
Fragment1.java

@SuppressLint("NewApi")
public class Fragment1 extends Fragment {

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment1, container);
	}

}
Fragment2.java
@SuppressLint("NewApi")
public class Fragment2 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment2, container);
	}

}

问题的原因在于Fragment在inflate的时候指定了container,在将其嵌套到其他的activity中的时候就报此错误,所以应将
inflater.inflate(R.layout.fragment2, container);
改为
return inflater.inflate(R.layout.fragment2, null);不能给它指定父控件,问题解决

</pre><pre name="code" class="java">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值