getActivity() 方法 获取到当前的activity
getFragmentManager() 方法 获取到fragment管理器;对应的是android.app.Fragment 支持Android4.0以上
getSupportFragmentManager() 对应的是import android.support.v4.app.Fragment; 为了兼容Android2.3
1.在layout 中新建一个 lay1.xml 文件
里面的内容可以根据你自己需要定义
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#158684" android:orientation="vertical" > <Button android:id="@+id/back" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/back" /> </LinearLayout>
2. 创建一个 fragmentone.java 文件 ,让它继承 Fragment ;重写 onCreateView
package com.debbi.fragment; import com.example.viewpager.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class fragmentfour extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.lay1, container, false); } }
3.将fragment 加载到activity 当中有两种方式;
3.1将fragment 添加到当前的activity 的布局文件当中去
<fragment android:id="@+id/framentfour" android:name="com.debbi.fragment.fragmentfour" android:layout_height="wrap_content" android:layout_width="match_parent"/>
3.2在当前的activity的代码中动态添加fragment
3.2.1
添加一个fragmenttransaction的实例 transaction
3.2.2
创建一个新的fragment的对象fragmentone的实例 fragmentexample
3.2.3
用transaction的add()方法添加 fragmentexample
3.3.4
用transaction的commit()方法是fragmenttransaction实例生效
FragmentManager fragmentManager =getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); RightFragment fragmentexample = new fragmentexample(); transaction.add(R.id.right, fragmentexample); transaction.commit();
浙公网安备 33010602011771号