动态的使用Fragment,出现异常The specified child already has a parent. You must call removeView

public class MainForActivity extends FragmentActivity implements OnClickListener{

private Button mTabWeixin; 
private contentFragment mWeixin; 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWeixin = new contentFragment(); 
setContentView(R.layout.activity_main_for);
mTabWeixin = (Button) findViewById(R.id.tab_bottom_weixin);
// 设置默认的Fragment 
setDefaultFragment();
}
private void setDefaultFragment() {
FragmentManager fm = getSupportFragmentManager(); 
FragmentTransaction transaction = fm.beginTransaction(); 
mWeixin = new contentFragment(); 
transaction.replace(R.id.id_content, mWeixin); 
transaction.commit(); 
}

 

public class contentFragment extends Fragment{

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) 

return inflater.inflate(R.layout.content_fragment, container, true); 
}
}

 

运行后发生异常,这段代码是从网上找的,抄下来的,为什么会错。最后发现是在使用 inflater.inflate(R.layout.content_fragment, container, true); 函数发生错误。

第三个参数为true,就将这个container作为根对象返回,否则仅仅将这个root对象的LayoutParams属性附加到resource对象的根布局对象上,也就是布局文件resource的最外层的View上

因为我的代码里是要把content_fragment放主页面activity_main_for上的,主页面是跟布局对象,调用inflate是为了得到view对象,然后附加到根对象content_fragment的布局上的。所以第三个参数要改成false

 

另外介绍一下android LayoutInflater.inflate()的参数及其用法

LayoutInflater类的用法,以及inflate()方法参数的含义,解释如下:

inflate()的作用就是将一个用xml定义的布局文件查找出来,注意与findViewById()的区别,inflate是加载一个布局文件,而findViewById则是从布局文件中查找一个控件。

 

1.获取LayoutInflater对象有三种方法

LayoutInflater inflater=LayoutInflater.from(this);
LayoutInflater inflater=getLayoutInflater();
LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);

 

2.关于LayoutInflater类inflate(int resource, ViewGroup root, boolean attachToRoot)方法三个参数的含义

resource:需要加载布局文件的id,意思是需要将这个布局文件中加载到Activity中来操作。

root:需要附加到resource资源文件的根控件,什么意思呢,就是inflate()会返回一个View对象,如果第三个参数attachToRoot为true,就将这个root作为根对象返回,否则仅仅将这个root对象的LayoutParams属性附加到resource对象的根布局对象上,也就是布局文件resource的最外层的View上,比如是一个LinearLayout或者其它的Layout对象。

attachToRoot:是否将root附加到布局文件的根视图上

 

第二种情况,其实是一个原理:在mvvm架构中在fragment中加载布局,我知道的有两种:

1.

bindingView = DataBindingUtil.setContentView(this, R.layout.activity_main);

2.

bindingView = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment, null, false);

然后return  bindingView.getRoot();在fragment中或者dialog中使用第二种则不会报错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值