一、简单使用
- 定义碎片布局
<?xml version="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Fragment"/>
</LinearLayout>
- 新建TestFragment类,继承自Fragment(使用support-v4库中的Fragment)
- 重写onCreateView 方法,填充 1 中 定义的布局
public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Viewview = inflater.inflate(R.layout.fragment_test,container,false);
returnview;
}
- 在使用的布局(主布局)中,引入Fragment,痛过android:name指定使用的fragment
<fragment
android:id="@+id/test_fragment"
android:name="com.example.test.TestFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
二、动态添加
- 重写主布局activity_main,添加一个帧布局用于添加碎片
<?xml version="1.0"encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/change_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="动态添加碎片"/>
<fragment
android:id="@+id/test_fragment"
android:name="com.example.test.TestFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/layout_test"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
- 在活动中实现动态添加碎片的功能
publicclass MainActivity extends AppCompatActivity {
@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button changeFragment = (Button)findViewById(R.id.change_fragment);
changeFragment.setOnClickListener(newView.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment(newTestFragment());
}
});
}
private void replaceFragment(Fragmentfragment) {
FragmentManager manager =getSupportFragmentManager();
FragmentTransaction transaction =manager.beginTransaction();
transaction.replace(R.id.layout_test,fragment);
transaction.addToBackStack(null);//可以不用,看需求
transaction.commit();
}
}
动态添加碎片步骤:
- 创建碎片实例;
- 获取FragmentManager,活动中可直接调用getSupportFragmentManager() --support-v4包的用法
--app包 getFragmentManager();
- 开启事务
- 向容器添加或替换碎片,一般使用replace(),第一个参数为容器,第二个参数为替换后的碎片
- 提交事务
三、碎片与活动的通信
- 活动调碎片,类似于findViewById()
getSupportFragmentManager().findFragmentById(R.id.test_fragment)
- 碎片调活动
getActivity()
ps:当碎片需要Context对象时。也可以调用getActivity(),因为活动也是Context对象