Fragment应用

使用母页和子页配合展示内容;母页和子页都有自己的activity。

母页是含有frameLayout控件的页面。子页通过配置,在frameLayout控件中显示;frameLayout本身没有任何内容。

-------------------------------------------------------------------------------------------------------------------------------------------------------------

母页内容(test_activity_fragment.xml)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragmentContainer" >

</FrameLayout>

在母页的activity中对FrameLayout控件配置子页。子页就是标准的Android XML File。

如何对FrameLayout控件配置子页

FragmentManager对象,母页activity管理所有的子页。
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity_fragment);
        FragmentManager fm = getFragmentManager();
        //找到含有fragment的视图,先在FragmentManager中,沒有就創建,并添加到FragmentManager
        Fragment fragment = fm.findFragmentById(R.id.test1_fragment);
        if (fragment == null) {
            fragment = new CrimeFragment();//使用子页的activity
            fm.beginTransaction().add(R.id.test1_fragment, fragment).commit();//子页给哪个frameLayout显示,在add方法中配置,
        }
    }

子页和activity的匹配是onCreateView方法

@Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_crime, container, false);


        mTitleField.setText(mCrime.getTitle());
        
     return v;

    }
原文地址:https://www.cnblogs.com/snake1118/p/11837254.html