プログラムで作成して、1つの画面に複数のフラグメントを表示しようとしています。各フラグメントをアクティビティレイアウトファイルに含めることで、これを問題なく行うことができます。しかし、私がプログラムでそれをやろうとすると、私は混乱します。これは、画面上の2つのフラグメントについてこれまでに持っているものです。
メインクラス:
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentOne one = new FragmentOne();
FragmentTwo two = new FragmentTwo();
FragmentThree three = new FragmentThree();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.imOne, one, "fragmentone");
ft.add(R.id.imTwo, two, "fragmenttwo");
ft.add(R.id.imThree, three, "fragmenthree");
ft.commit();
}
}
フラグメント1:
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_one, container, false);
return view;
}
}
フラグメント2:
public class FragmentTwo extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.frag_two, container, false);
return view;
}
}
私の2つのフラグメントクラスのレイアウトファイルには、単純なTextViewが含まれています。そして、私のメインクラスのactivity_main.xmlレイアウトファイル:
<?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="horizontal" >
<FrameLayout
android:id="@+id/imOne"
android:name="com.david.twofragexample.FragmentOne"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="@+id/imTwo"
android:name="com.david.twofragexample.FragmentTwo"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
<FrameLayout
android:id="@+id/imThree"
android:name="com.david.twofragexample.FragmentThree"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2" />
</LinearLayout>
プログラムで実行しようとすると、activity_main.xmlファイルに何を含めるべきか混乱します。したがって、Android開発者ガイド(http://developer.android.com/guide/components/fragments.html)から、
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentOne fragment = new FragmentOne();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
したがって、このコードをonCreateメソッドに追加すると、プログラムでこれを行うために、activity_main.xmlファイルにどのような変更を加える必要がありますか?R.id.fragment_containerがどこから来ているのかわかりません。画面のどこに新しいフラグメントが表示されるかをどのように判断できますか?ありがとうございます
編集:私はこれを電話ではなくタブレットで開発しています。これは解決され、上記のコードはプログラムで3つのフラグメントを追加します。