在activity中更新fragment中的界面

MainActivty

  1. 添加fragment
for (int i = 0; i < 6; i++) {
            mList.add(MyFragment.newInstence(i));
        }
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        adapter = new MyViewpagerAdapter(supportFragmentManager, mList);
        viewpager.setOffscreenPageLimit(10);
        viewpager.setAdapter(adapter);
  1. MyViewpagerAdapter.java
public class MyViewpagerAdapter extends FragmentStatePagerAdapter {

    private ArrayList mList_fragment;

    public MyViewpagerAdapter(FragmentManager fm, ArrayList mList_fragment) {
        super(fm);
        this.mList_fragment = mList_fragment;
    }

    public MyViewpagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        return mList_fragment.get(position);

    }

    @Override
    public int getCount() {
        return mList_fragment.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return PagerAdapter.POSITION_NONE;
    }
}

Fragment

  • 传入数据
public static MyFragment newInstence(int index) {
        MyFragment fragment = new MyFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        index = getArguments().getInt("index");
        setStr(index + "");
    }

操作数据改变界面

以下操作均在activity中

  • 设置当前显示页
    viewpager.setCurrentItem(3)

  • 修改当前页的内容
    int currentItem = viewpager.getCurrentItem();
    mList.get(currentItem).setTextContext(“这是什么?”);

  • 删除当前页
    int currentItem = viewpager.getCurrentItem();
    mList.remove(currentItem);
    adapter.notifyDataSetChanged();

  • 添加页
    mList.add(MyFragment.newInstence(mList.size()));
    adapter.notifyDataSetChanged();
    viewpager.setCurrentItem(0);

你可能感兴趣的:(小笔记)