android - fragment : NullPointer with Adapter 内的 ViewPagerIndicator

标签 android android-fragments android-viewpager

我试过使用 this answer在 fragment 内使用带有指示器的 ViewPager,like so . (只是一个模型)。
有更改 fragment 的导航微调器。每个“页面”都包含一个 ListView。

所以基本上我在寻找:
SherlockFragmentActivity -> SherlockFragment -> ViewPager -> ListView

但是,当我尝试实现我在答案中看到的内容时,我遇到了 findViewById() 错误;
我认为这是因为我没有得到正确的“上下文”。

这是我的 fragment :

public class HomeViewFragment extends SherlockFragment {

    private ViewPager mPager;
    private HomePagerAdapter mAdapter;
    private TitlePageIndicator mIndicator;
    private Context context;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = getSherlockActivity().getApplicationContext();            

        mAdapter = new HomePagerAdapter(context);

        mPager = (ViewPager)context.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);

        mIndicator = (TitlePageIndicator)context.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
    } 

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}

最佳答案

第 1 步:删除 context = getSherlockActivity().getApplicationContext();

第 2 步:将 context.findViewById 替换为 getActivity().findViewById

第 3 步:将所有剩余的 context 替换为 getActivity()

第 4 步:删除您的 onActivityCreated() 实现,因为它没有做任何事情

第 5 步:下定决心永远不再使用 getApplicationContext(),除非您知道在特定情况下为什么需要它

关于android - fragment : NullPointer with Adapter 内的 ViewPagerIndicator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166050/

相关文章:

android - 如何使 AppBarLayout 在 windowTranslucentStatus 设置为 true 时完全消失

android - 在 Android Studio 上为 android 构建 OutsystemsNow 出现 dexException

android - 在 View 中缩放文本以适合?

java - 如何使用 androidx 从另一个 fragment 调用 fragment 方法

android - fragment 不启动服务

android - IllegalStateException:在 ViewPager 的 onSaveInstanceState 之后无法执行此操作

Android 服务 > Activity > 带有 ViewPager 的 fragment

android - BottomNavigationView - 如何更改菜单项字体?

android - Activity 已被销毁异常

android - 在 ViewPager 中实现弹性/弹跳动画效果的最佳方法是什么?