一、基本概念
Fragment的优点:
二、添加到Activity方法
1、静态方法:
创建各个Fragment.xml添加各自组件,然后创建对应的Fragment类并继承自Fragment,重写OnCreateView觉得Fragment的布局
public class Fragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1, container, false); } }
再在activity_main.xml中加入使用使用android:name前缀来引用各个Fragment,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" > <fragment android:id="@+id/fragment1" android:name="com.example.fragmentdemo.Fragment1" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> <fragment android:id="@+id/fragment2" android:name="com.example.fragmentdemo.Fragment2" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout>
主MainActivity自动生成。
2、动态添加
保留最外层的线性布局管理器,为其添加一个id
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" > </LinearLayout>
在MainActivity中修改:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display = getWindowManager().getDefaultDisplay(); if (display.getWidth() > display.getHeight()) { Fragment1 fragment1 = new Fragment1(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit(); } else { Fragment2 fragment2 = new Fragment2(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit(); } } }
首先获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:
1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。
2.开启一个事务,通过调用beginTransaction方法开启。
3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。
4.提交事务,调用commit方法提交。
只有activity可以使用WindowManager,否则应该使用Context.getResources().getDisplayMetrics()来获取。
Context.getResources().getDisplayMetrics()依赖于手机系统,获取到的是系统的屏幕信息;
WindowManager.getDefaultDisplay().getMetrics(xx)是获取到Activity的实际屏幕信息。
三、Fragment通信
尽管 Fragment 是作为独立于 Activity的对象实现,并且可在多个 Activity 内使用,但Fragment 的给定实例会直接绑定到包含它的 Activity。具体地说,Fragment 可以通过 getActivity() 访问 Activity实例,并轻松地执行在 Activity 布局中查找视图等任务。
View listView = getActivity().findViewById(R.id.list);
同样地,Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通过从 FragmentManager 获取对 Fragment 的引用来调用Fragment中的方法。
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
文章来源:https://www.cnblogs.com/cr330326/p/5712022.html
原文:https://www.cnblogs.com/liblogs/p/11468592.html