统一一个fragment,在activity中通过传值来改变数据

 1.在activity中:

统一一个fragment(相当于一个fragment的适配),生成不同对象,在activity中通过传值来改变数据

    private void initView() {
        titleDatas=new ArrayList<>();
        titleDatas.add("生词本");
        titleDatas.add("学习中");
        titleDatas.add("待复习");
        titleDatas.add("熟悉本");
        fragmentList = new ArrayList();
        IWordsNewDao newDao = new WordsNewImpl();
        for(Words_New word: newDao.select()){
            Words words = new Words(word.getWord(), word.getSymbol(), word.getExplain());
            dataList.add(words);
        }
        fragmentList.add(newInstance(dataList));
        fragmentList.add(newInstance(dataList));
        fragmentList.add(newInstance(dataList));
        fragmentList.add(newInstance(dataList));
        adapter = new StrangeFragmentAdapter(getSupportFragmentManager(), titleDatas, fragmentList);

    }

    /**
     * Method name : newInstance
     * Specific description :传递数据给fragment
     *@param
     *@param
     *@return
     */
    public static StrangeListFragment newInstance(List dataList ) {
        StrangeListFragment fragment = new StrangeListFragment();
        Bundle bundle = new Bundle();
        WordList wordList = new WordList();
        wordList.setData(dataList);
        bundle.putSerializable("dataList",wordList);
        fragment.setArguments(bundle);
        return fragment;
    }

2.在fragmnet中:

传的是一个list

    private List initList() {
        WordList dataBean = (WordList)getArguments().getSerializable("dataList");
//避免报空指针异常,重新创建了mData,并添加了data
        dataList = dataBean.getData();
        LogUtils.d(dataList.toString());
        return dataList;
    }

 传的是一个普通的String

    public void setData(){
//        mtv_title.setText(pager.mtitle);
        String content = getArguments().getString("content");
        LogUtils.d(content);
        mtv_content.setText(content);
    }

3.注意:如果是传一个list集合,需要序列化

public  class WordList implements Serializable {

   private List data;

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }
}

 

你可能感兴趣的:(安卓学习)