假设你有 fragment_container.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fraContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
你需要做的是用你的程序中的一个片段替换这个容器,例如:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
if (findViewById(R.id.fraContainer) != null)
{
MyFragmentA myFragment = new MyFragmentA();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fraContainer, myFragment)
.commit();
}
}
这会将片段布局(容器)替换为您想要的片段。
现在让我们检查 MyFragmentA 和 MyFragmentB
public class MyFragmentA extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_both, container, false);
TextView x = (TextView)view.findViewById(R.id.textView);
x.setText("I am fragment A");
return view;
}
...
还有第二个片段
public class MyFragmentB extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_both, container, false);
TextView x = (TextView)view.findViewById(R.id.textView);
x.setText("I am fragment B");
return view;
}
...
通过引用视图对象,都膨胀了相同的fragment_both.xml,并且都使用相同ID的相同TextView!
希望能帮助你理解。