今天学习了Fragment的用法,了解它的基本原理和生命周期,以及常用方法。可是在动态向Activity中加入Fragment或替换Fragment时总是出现如下错误:
在网上找了很久的资料,都没有找到关于Fragment相关的这类错误。只是知道这是“根”错误。困惑……
下面我就从头开始,我所做的例子:
这是Activity的布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/contair"
>
<TextView
android:id="@+id/tv_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<fragment
class="cdu.xiaohui.FragmentView1"
android:id="@+id/frag1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:id="@+id/linear"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></LinearLayout>
</LinearLayout>
在布局文件中,有一个fragment元素,有一个内嵌的LinearLayout,该layout是用来装另一个fragment
继续……
Fragment布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Fragment"
/>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点击"
/>
</LinearLayout>
fragment中有一个Button,后来绑定了点击事件,点击之后就增加一个fragment。
下面是第一个fragment,是通过元素引进了(在之前的activity布局中的fragment元素):
public class FragmentView1 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.frag1, container);
Button button1=(Button)view.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
FragmentTransaction tran=getActivity().getFragmentManager().beginTransaction();
FragmentView2 frag2=new FragmentView2();
tran.replace(R.id.frag1, frag2);
tran.commit();
}
});
return view;
}
}
下面是第二个Fragment:
public class FragmentView2 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag2, container);
}
}
打包运行后,总是出现上述错误。为什么呢?
进过反复调试,总有弄明白了
事情是这样的,问题出现在第二个Fragment喔,“根”错误。所谓一女不能嫁二夫,这里就是为一个Fragment对象指定了两个根容器。
Fragment对象的onCreateView方法中,如果使用了container作为根(我这里就使用了),那么在使用tran.replace()或add()方法,需要指定一个根,如果两个地方都指定了,就会出现上述错误。