首页 > 其他 > 详细

关于Fragment的简单使用

时间:2016-08-23 17:14:28      阅读:190      评论:0      收藏:0      [点我收藏+]
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();



本文出自 “残破的城堡” 博客,请务必保留此出处http://wh201503.blog.51cto.com/10047381/1841422

关于Fragment的简单使用

原文:http://wh201503.blog.51cto.com/10047381/1841422

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!