您可以通过创建一个Activity 来实现这一点,该Activity 顶部有你的不可见布局,FrameLayout 作为Fragments 的容器:
MainActivit.java
public class MainActivity(){
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
}
}
和activity_main.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/invisible_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<!-- your other views here -->
</LinearLayout>
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/invisible_menu" />
</RelativeLayout>
这就是MainActivity,它将保存您所有的Fragments。要在您的应用中使用Fragments,您应该检查Android Developers - Fragments
编辑:您可以通过以下代码添加/替换Fragments:
要添加您的第一个 Fragment,只需致电:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
ExampleFragment fragment = new ExampleFragment();
transaction.add(R.id.fragment_container, fragment);
transaction.commit();
// Commit the transaction
transaction.commit();
然后用另一个 Fragment 替换内容,你应该在你的 onClick 中做这样的事情:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
所以基本上你应该使用FragmentTransaction.add() 和FragmentTransaction.replace()。