2012-04-15 68 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

相關問題