0

我正在使用本教程 - 以编程方式添加片段

我完全按照该教程中的方式进行操作,但发现此错误-

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentdemo/com.example.fragmentdemo.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

这是我的代码

public class MainActivity extends FragmentActivity {

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

           // get an instance of FragmentTransaction from your Activity
           FragmentManager fragmentManager = getSupportFragmentManager();
           FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

           //add a fragment
           simpleFragment myFragment = new simpleFragment();
           fragmentTransaction.add(R.id.myfragment, myFragment);
           fragmentTransaction.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;
    }

}

public class simpleFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.simple_fragment,container);
        return view;
    }



}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="horizontal" >

   <TextView
       android:layout_width="0px"
       android:layout_weight="1"
       android:layout_height="match_parent"
       android:text="It's TextView in main Activity"
       android:background="#555555"/>
   <LinearLayout
       android:id="@+id/myfragment"
       android:layout_width="0px"
       android:layout_weight="4"
       android:layout_height="match_parent" />

</LinearLayout>

布局 2

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="It's Fragment" />
   <ImageView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:src="@drawable/ic_launcher"/>
</LinearLayout>
4

0 回答 0