1、Fragment是为了避免Activity使用的时候,因为不断频繁创建和销毁时消耗时间的这种情况
2、其特点:Fragment是轻量级的Activity,Fragment的使用时不需要再清单文件中注册
(碎片在平板和大屏幕上使用的比较广泛)
Fragment的使用:
一:静态使用Fragment
静态使用就是把Fragment当成普通的控件,直接写在Activity的布局文件中。
使用步骤:
1、创建类,并继承Fragment
2、重写Fragment的onCreateView()生命周期方法,并返回一个View
3、在布局文件中使用<fragment android:name="自定义Fragment的类路径" />
注意:这个fragment必须要有唯一的标记,如tag或者id
**创建Fragment类的代码:
public class NewFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_new, container, false);
}
}
**在布局文件中的代码:
<TextView
android:layout_marginTop="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示Fragment" />
<fragment
android:name="com.hf.practicedemo.NewFragment"
android:id="@+id/newfragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
结果展示:
二、动态使用Fragment
首先:需要在要显示的页面中,的布局文件中占位
然后是:
在Activity中:1, 得到Fragment的管理器对象
2, 开启Fragment的事务处理
3, 实例化要显示的Fragment 里面进行对数据的操作
4, 动态显示Fragment
5, 提交事务
在xml文件中的代码:
使用布局占位
<LinearLayout
android:id="@+id/newfragment_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
在Activity中的代码:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
NewFragment myfrg = new NewFragment();
fragmentTransaction.replace(R.id.newfragment_id,myfrg);
fragmentTransaction.commit();
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。