通过Listener在Activity和ViewPagerAdapter之间进行通信

时间:2017-03-14 14:33:31

标签: android android-fragments android-viewpager

我有一个带有TabLayout的Activity,其中包含2个Tabs,每个Tab都有自己的Fragment。我的活动中有一个Fab按钮。当我在选项卡1中单击它时,我想以某种方式向ViewPagerAdapter的getItem()方法指示"嘿,单击了Button。将选项卡1中的现有片段替换为另一个片段。"

我不知道该怎么做。我在想可能会添加一个监听器但又不知道如何实现它。任何帮助将不胜感激。

主要活动:

public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private ArrayList<Fragment> fragments = new ArrayList<>();
private ArrayList<String> titles = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing_toolbar);
    setSupportActionBar(toolbar);

    fragments.addAll(Arrays.asList(new Tasks(),new Calendar(),new Contacts()));
    titles.addAll(Arrays.asList(getResources().getString(R.string.fragment_task_title),
            getResources().getString(R.string.fragment_cal_title),getResources().getString(R.string.fragment_contacts_title)));
    TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs);

    final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.hide();

    viewPager = (ViewPager)findViewById(R.id.container);
    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragments,titles);
    viewPager.setAdapter(viewPagerAdapter);
    viewPager.setCurrentItem(1);
    viewPager.addOnPageChangeListener(new 
    tabLayout.setupWithViewPager(viewPager);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fabAction();
        }
    });

    if (savedInstanceState==null){
        if (getSupportActionBar()!=null){
            getSupportActionBar().setDisplayShowTitleEnabled(true);
        }
    }
}
public void fabAction(){
    int current = viewPager.getCurrentItem();

    switch (current){
        case 0:{
            //TELL THE VIEWPAGER ADAPTER THAT BUTTON IS CLICKED AND SWITCH FRAGMENTS
            break;
        }
        case 1:{
            Toast.makeText(this, "IN TAB 2", Toast.LENGTH_LONG).show();
            break;
        }
    }
}}

ViewPagerAdapter:

public class ViewPagerAdapter extends FragmentPagerAdapter{
ArrayList<Fragment> fragments;
ArrayList<String> titles;
private Fragment mFragmentAtPos0;
private FragmentManager fragManager;

//NEED TO IMPLEMENT THE LISTENER IN THIS CLASS TELLING ME THAT THE BUTTON WAS CLICKED IN MAIN ACTIVITY
public ViewPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments, ArrayList<String>titles) {
    super(fm);
    this.fragments = fragments;
    this.titles = titles;
    fragManager = fm;

}

@Override
public Fragment getItem(int position) {
    //Somehow get Indication Here that the button was clicked

    if (position == 0)
    {
        if(mFragmentAtPos0==null){
            mFragmentAtPos0 = new Tasks();
            fragManager.beginTransaction().replace(R.id.container,mFragmentAtPos0).commit();
            notifyDataSetChanged();
        }
        return mFragmentAtPos0;
    }else{
        return fragments.get(position);

    }

}

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

@Override
public CharSequence getPageTitle(int position) {

    return titles.get(position);
}

@Override
public int getItemPosition(Object object)
{
    if (object instanceof Tasks && mFragmentAtPos0 instanceof AddContact)
        return POSITION_NONE;
    return POSITION_UNCHANGED;
}}

这就是我尝试过的事情,并从@ wize对类似问题的回答中得到了我的想法。答案中有太多缺失的部分让我掌握整个解决方案:Replace Fragment Inside ViewPager

1 个答案:

答案 0 :(得分:1)

这确实有点棘手。也许您应该考虑将fab移动到要更改的片段,并处理片段内的更改。如果fab必须在Activity中,您可以从Pager Adapter本身添加/删除片段。

适配器看起来像这样:

    public class CodebaseFragmentPagerAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> mFragmentList = new ArrayList<Fragment>();

    public CodebaseFragmentPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    public void removeItem(int position){
        mFragmentList.remove(position == 0 ? 0 : position - 1);
        this.notifyDataSetChanged();
    }

    public void clearAllItems(){
        mFragmentList.clear();
        this.notifyDataSetChanged();
    }

    public void updateItem(int position, Fragment fragment){
        mFragmentList.set(position, fragment);
        notifyDataSetChanged();
    }

    @Override
    public int getItemPosition(Object object) {
        if (mFragmentList.contains(object)) return mFragmentList.indexOf(object);
        else return POSITION_NONE;
    }

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

    public void addFrag(Fragment fragment) {
        mFragmentList.add(fragment);
        notifyDataSetChanged();
    } 
}

注意:上面的适配器不支持标签布局,因此可以随意调整它以满足您的需求

用法:

 mAdapter = new CodebaseFragmentPagerAdapter(getSupportFragmentManager());
 mViewPager.setAdapter(mAdapter);

 mAdapter.addFrag(FragmentExample.newInstance());