我试图通过编程创建它们在一个屏幕上显示多个片段。我可以通过将每个片段包含到活动布局文件中来解决这个问题。然而,当我尝试以编程的方式进行编辑时,我感到困惑。这就是我迄今为止在屏幕上显示的两个片段。如何以编程方式创建多个片段?
主类:
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();
}
}
片段一:
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;
}
}
片段二:
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;
}
}
为我的两个片段类的布局文件只包含一个简单的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来自。我怎样才能确定我的新片段将在屏幕上的位置?谢谢
编辑:我正在开发此平板电脑,而不是一个phone.This现在已经解决,上述代码将以编程方式添加三个片段。
你的'activity_main.xml'中有'fragment_container'元素吗? – Audrius
是的,只是在那里添加了谢谢 – DMC