博客
关于我
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 中 3 个不可思议的返回功能
查看>>
python 中 dict 的另一种用法
查看>>
Python 中 PIL 读取图片出现异常旋转的解决方法
查看>>
Python 中只有一个 True 和一个 False 对象吗?
查看>>
python读取mtcars数据集并实现以下操作_关于数据处理。。,Python交流,技术交流区,鱼C论坛 - Powered by Discuz!...
查看>>
Python 中多线程与多处理之间的区别
查看>>
Python 中如何使用 lambda 函数
查看>>
Python 中如何创建多行字符串?
查看>>
Python 中如何处理异常?
查看>>
Python 中如何实现列表的切片?
查看>>
Python 中如何实现字典的排序?
查看>>
Python 中常用的数据类型及相关操作详解
查看>>
Python 中的离线语音转文本
查看>>
Python 中的线程
查看>>
Python 中的继承机制是什么样的?
查看>>
Python 中的装饰器是什么?
查看>>
Python 中的装饰器是如何工作的,有哪些实际应用场景?
查看>>
python读excel
查看>>
Python 中读取 CSV 文件-ChatGPT4o作答
查看>>
python请求html_使用Python请求获取HTML?
查看>>