2012-04-15 39 views
2

我试过使用this answer在片段中使用带指示符的ViewPager,like so。 (只是一个模拟)。
有更改片段的导航微调器。每个“页面”将包含一个ListView。片段内的ViewPagerIndicator:NullPointer与适配器

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

然而,当我尝试并实现了我的答案,我得到一个错误与findViewById看到();
我认为这是因为我没有得到正确的“上下文”。

这里是我的片段:

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

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

第2步:更换context.findViewByIdgetActivity().findViewById

第3步:用getActivity()

替换的 context所有剩余事件

步骤#4:删除您的onActivityCreated()我mplementation,因为它没有做任何事情

第五步:解决您将不会再使用getApplicationContext()除非你知道明确为什么需要它在特定的环境

+0

findViewById是不是在片段的方法但是,我应该在那里做什么? 而我的适配器需要传递给它的上下文,而不是片段。 – osxoep 2012-04-15 21:15:07

+0

@osxoep:对不起,我没有给予足够的关注。我编辑了我的答案。 – CommonsWare 2012-04-15 21:17:08

+0

谢谢,这建立了我的代码,但现在我有另一个错误。我知道今晚我在做什么:) – osxoep 2012-04-15 22:20:23