使用RxJava的Android TabLayout和ViewPager Fragment

时间:2018-03-31 04:16:05

标签: android android-fragments android-viewpager rx-java android-tablayout

假设我有一个拥有2个片段的ViewPager。从那些片段中,我创建了一个PublishSubject,我想在MainActivity中订阅它。但是,问题是在onCreate()期间,我无法从Fragment中获取特定的PublishSubject,因为它似乎尚未创建。因此,如果我试图订阅它,我最终会得到NPE。

一旦ViewPager创建片段到MainActivity,有没有办法传递PublishSubject?或者我应该尝试做别的事情。我已经尝试了解其他问题,但我找不到任何与此类似的东西。

一些代码来说明我的意思:

片段

public class ExampleFragment extends Fragment {
    PublishSubject<SomeObject> mPublishSubject = PublishSubject.create();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
          // Regular fragment stuff here
    }

    public PublishSubject<SomeObject> getPublishSubject() {
        return mPublishSubject;
    }
}

ViewPager

public class ExamplePagerAdapter extends FragmentStatePagerAdapter {
    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0: 
                return new ExampleFragment();
            case 1:
                return new SomeOtherFragment();
            default:
                return null;
        }
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {
    private PublishSubject<SomeObject> mSubjectFromTheFragment;
    private ExamplePagerAdapter mPagerAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("tab1"));
        tabLayout.addTab(tabLayout.newTab().setText("tab2"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mPagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        mViewPager.setAdapter(mPagerAdapter);

        // Set listener
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            // Code to implement the methods
        });

        // When or where do I set PublishSubject
        mPublishSubject = ?

        // The subscription
        mPublishSubject.observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(/** Some new Action1<> etc. **/ )
    }

}

非常感谢任何帮助或指向某种方向!

0 个答案:

没有答案