實現上述功能步驟:
步驟一:將DrawerLayout添加到佈局文件中,並書寫兩個FrameLayout,後續使用主內容頁面以及側滑頁面代替FrameLayout
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<FrameLayout
android:id="@+id/fl_left"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="left">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
步驟二:書寫主內容Fragment的佈局文件以及側滑Fragment的佈局文件
<?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="vertical">
<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5f00"
android:gravity="center"
android:text="我是主內容界面"
android:textColor="#000"
android:textSize="17sp"/>
</LinearLayout>
<?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="vertical">
<TextView android:layout_width="200dp"
android:layout_height="match_parent"
android:background="#50f0"
android:text="我是側滑界面"
android:textColor="#000"
android:textSize="17sp"/>
</LinearLayout>
步驟三:將各自的佈局文件添加到自己的Fragment中
public class ContentFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View contentView = View.inflate(getContext(), R.layout.fragment_content, null);
return contentView;
}
}
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View contentView = View.inflate(getContext(), R.layout.fragment_left, null);
return contentView;
}
}
public class MainActivity extends AppCompatActivity {
private static final String TAG_CONTENT ="TAG_CONTENT" ;
private static final String TAG_LEFT ="TAG_LEFT" ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fl_content,new ContentFragment(),TAG_CONTENT);
ft.replace(R.id.fl_left,new LeftFragment(),TAG_LEFT);
ft.commit();
}
}
完成收工!!!
Demo源碼下載地址:http://download.csdn.net/detail/k2514091675/9802435