Fragment動態新增頁面
阿新 • • 發佈:2018-11-30
一.首先將fragment準備好
包含兩部分,一部分是佈局檔案,一部分是類
1.佈局檔案:普通的佈局檔案就行
<?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:background="#afc" android:orientation="vertical"> <Button android:id="@+id/bt_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="按鈕" /> </LinearLayout>
2.類:在類中引入佈局檔案
package com.example.administrator.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class LeftFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment, container); return view; } }
二,activity裡新增fragment
包含兩部分,一部分是在activity佈局檔案中給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="horizontal"> <FrameLayout android:id="@+id/left" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"></FrameLayout> </LinearLayout>
那個FrameLayout就是將來被替換為fragment的物件
然後再在activity程式碼中動態新增fragment
FragmentManager mannager = getSupportFragmentManager();
FragmentTransaction tronsaction = mannager.beginTransaction();
tronsaction.replace(R.id.left, 要替換的fragment);
tronsaction.addToBackStack(null);
tronsaction.commit();