私はこのチュートリアルを使用しています -プログラムでフラグメントを追加します
そのチュートリアルとまったく同じようにしましたが、このエラーが見つかりました-
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>