根据viewpager位置更改适配器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据viewpager位置更改适配器相关的知识,希望对你有一定的参考价值。

我有一个viewpager有3页但内部有一个片段(带有循环视图)。我想根据页面Im改变片段的内容,所以我不需要创建3个片段。只需一个并适应它。为此,我在视图页面上获取当前位置并将其发送到我的片段活动,以便我可以更改adpater,但我总是会遇到“...在空对象引用上”的错误。

在我的活动中,我有:

public class HintsActivity extends AppCompatActivity {

    private ViewPager ViewPagerHints;
    private hintFragment hintfragment = new hintFragment();

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        ViewPagerHints = findViewById(R.id.viewPagerHints);
        if (ViewPagerHints != null) {
            setupViewPager(ViewPagerHints);
        }

        ViewPagerHints.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {}
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            public void onPageSelected(int position) {
                hintfragment.changeAdapter(position);
            }
        });

        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(ViewPagerHints);

        setTitle("Hints");
    }

    private void setupViewPager(ViewPager myViewPager) {
        Adapter adapter = new Adapter(getSupportFragmentManager());

            adapter.addFragment(new hintFragment(), "Foods");
            adapter.addFragment(new hintFragment(), "Sports");
            adapter.addFragment(new hintFragment(), "Health");

        myViewPager.setAdapter(adapter);

    }

    static class Adapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();
        private final List<String> mFragmentTitles = new ArrayList<>();

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

        public void addFragment(Fragment fragment, String title) {
            mFragments.add(fragment);
            mFragmentTitles.add(title);
        }

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

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitles.get(position);
        }
    }
}

在我的片段活动(hintFragment)中:

public class hintFragmen textends Fragment {

private RecyclerView recyclerView;
private Adapter_Hints adapter_hints;
private HintsManager hintsManager= new HintsManager ();
private List<Hint> hintsListFoods ;
private List<Hint> hintsListHealth;
private List<Hint> hintsListSports;

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    recyclerView = (RecyclerView)inflater.inflate(R.layout.fragment_hints, container, false);
    recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));

    hintsListFoods = hintsManager.getFoodsHints();

    adapter_hints = new Adapter_Hints(hintsListFoods);
    recyclerView.addItemDecoration(new MyDividerItemDecoration(recyclerView.getContext(), LinearLayoutManager.VERTICAL, 16));
    recyclerView.setAdapter(adapter_hints);

    return recyclerView;
}

public void changeAdapter(int position) {
        switch (position) {
            case 0:
                hintsListFoods = hintsManager.getFoodsHints();
                adapter_hints= new Adapter_Hints(hintsListFoods);
                recyclerView.setAdapter(adapter_hints);
                break;
            case 1:
                hintsListSports= hintsManager.getSportHints();
                adapter_hints= new Adapter_Hints(hintsListSports);
                recyclerView.setAdapter(adapter_hints);
                break;
            case 2:
                hintsListHealth= hintsManager.getHealthHints();
                adapter_hints= new Adapter_Hints(hintsListHealth);
                recyclerView.setAdapter(adapter_hints);
                break;
        }
    }

fragment_hints.xml

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recycleViewHints"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

日志:

12-21 10:19:38.468 30243-30243/com.support.android.iplfit E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.support.android.iplfit, PID: 30243
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
                                                                                at com.support.android.iplfit.hintFragment.changeAdapter(hintFragment.java:57)
                                                                                at com.support.android.iplfit.Activities.hintFragment$1.onPageSelected(HintsActivity.java:46)
                                                                                at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1939)
                                                                                at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:679)
                                                                                at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:663)
                                                                                at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2255)
                                                                                at android.view.View.dispatchTouchEvent(View.java:9943)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2663)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2344)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2669)
                                                                                at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2358)
                                                                                at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:411)
                                                                                at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1810)
                                                                                at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                                                                at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
                                                                                at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
                                                                                at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:373)
                                                                                at android.view.View.dispatchPointerEvent(View.java:10163)
                                                                                at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4434)
                                                                                at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4302)
                                                                                at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                                at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                                at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                                at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3995)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                                at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4052)
                                                                                at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                                at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3902)
                                                                                at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3868)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3876)
                                                                                at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3849)
                                                                                at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6210)
                                                                                at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6184)
                                                                                at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6145)
                                                                                at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6313)
                                                                                at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
                                                                                at android.os.MessageQueue.nativePollOnce(Native Method)
                                                                                at android.os.MessageQueue.next(MessageQueue.java:323)
                                                                                at android.os.Looper.loop(Looper.java:136)
12-21 10:19:38.468 30243-30243/com.support.android.iplfit E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
答案

您已在Activity类中初始化了对象hintfragment,该对象未扩展到任何父视图。因此,当您尝试更改ViewPager的页面时,您将获得空指针异常。请尝试以下代码。

ViewPagerHints.addOnPageChangeListener(new 
ViewPager.OnPageChangeListener() {
        public void onPageScrollStateChanged(int state) {}
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        public void onPageSelected(int position) {
            ((hintFragment)((Adapter)ViewPagerHints.getAdapter()).getItem(position)).changeAdapter(position);
        }
    });
另一答案

试试这个::

private View rootView;

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_hints, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerViewId);
    recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));

    ...
    return rootView;
}

以上是关于根据viewpager位置更改适配器的主要内容,如果未能解决你的问题,请参考以下文章

使用 viewpager 创建多个片段

Android ViewPager 适配器修改其他页面

如何使用 viewpager 和片段为我的 ListView 设置适配器

Viewpager 不清除片段

FragmentStatePagerAdapter 内存泄漏(带有 viewpager 的嵌套片段)

通过按钮更改 viewpager 片段 Click