博客
关于我
Android 开发学习进程0.26 fragment的工厂实例化
阅读量:418 次
发布时间:2019-03-06

本文共 2070 字,大约阅读时间需要 6 分钟。

android fragment的工厂实例化

在刚开始使用fragment时,总会习以为常的使用fragment的构造函数传值,但有时这会导致 fragment无法恢复状态的错误,这是由于fragment恢复状态时传bundle时默认的构造方法已经被占用的缘故。同时谷歌也不建议我们这样做,如默认创建的bankfragment样板代码就是使用工厂模式创建实例的,现在直接分析一下这种方式。
首先简单使用动态创建fragment的方法,在activity中向fragment传值如下

  mList=new ArrayList<>();     mList.add("sssss");     mList.add("sssss2");     mList.add("sssss3");     mList.add("sssss4");     fragmentManager=getSupportFragmentManager();     fragmentTransaction=fragmentManager.beginTransaction();     fragmentTransaction.add(R.id.framelayout,BlankFragment.newInstance("text",mList));     fragmentTransaction.commit();

这里使用fragmentmanager获取fragmenttransaction 然后在transacation中添加 fragment的实例化方法。而fragment的主要代码有下:

public class BlankFragment extends Fragment {      private static final String ARG_PARAM1 = "param1";    private static final String ARG_PARAM2 = "param2";    private String mParam1;    private ArrayList<String> mParam2;    private TextView textView;    public BlankFragment() {    }    public static BlankFragment newInstance(String param1, ArrayList<String> param2) {        BlankFragment fragment = new BlankFragment();        Bundle args = new Bundle();        args.putString(ARG_PARAM1, param1);        args.putStringArrayList(ARG_PARAM2, param2);        fragment.setArguments(args);        return fragment;    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        if (getArguments() != null) {            mParam1 = getArguments().getString(ARG_PARAM1);            mParam2 = getArguments().getStringArrayList(ARG_PARAM2);        }    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        View view= inflater.inflate(R.layout.fragment_blank, container, false);        textView =view.findViewById(R.id.tvfragment);        textView.setText(mParam1+mParam2);        return view;    }}

这里可以分析下,创建了静态实例化方法 newinstance 里面参数可以根据需求自己来定,将参数添加到bundle中,再使用setArgument方法绑定到fragment中。在fragment的onCreate方法中取出,这样就避免了使用构造函数传值的问题。

转载地址:http://gdpkz.baihongyu.com/

你可能感兴趣的文章
python | webassets,一个超强的 Python 库!
查看>>
python | werkzeug,一个不可思议的 Python 库!
查看>>
python | xlsxwriter,一个实用的 Python 库!
查看>>
python | xlwings,一个非常实用的 Excel 相关的 Python 库!
查看>>
python读取含中文的json
查看>>
python | 提升代码迭代速度的Python重载方法
查看>>
python | 深入理解Python并发编程中的GIL限制与解决方案
查看>>
Python | 爬虫实战——亚马逊搜索页监控(附详细源码)
查看>>
python | 高效使用Python工具自动生成模块文档的秘诀
查看>>
python 一个list去除另一个list中的值
查看>>
python 三大框架的 介绍。
查看>>
Python 下载的 11 种姿势,一种比一种高级!
查看>>
python读取一个文件夹下所有图片_初学Python-找出文件夹下的所有图片
查看>>
Python 中 3 个不可思议的返回功能
查看>>
python 中 dict 的另一种用法
查看>>
Python 中 PIL 读取图片出现异常旋转的解决方法
查看>>
Python 中只有一个 True 和一个 False 对象吗?
查看>>
python读取mtcars数据集并实现以下操作_关于数据处理。。,Python交流,技术交流区,鱼C论坛 - Powered by Discuz!...
查看>>
Python 中多线程与多处理之间的区别
查看>>
Python 中如何使用 lambda 函数
查看>>