2014-10-10 111 views
0

我已經開始使用Android Studio的預先定義的帶片段的佈局(SectionsPagerAdapter,ViewPager)編碼一個小應用。Android:從MainActivity訪問片段實例

我得在MainActivity.class主/ UI線程運行的任務,在一個點顯示了的onClick方法

@Override 
     public void onClick(DialogInterface dialog, int which) { 
      category = eventsToDisplay.get(which); 
      averageFragment.category = category; 
      dialog.dismiss(); 
     } 

一個對話框,但我不能讓averageFragment.category = category;分配工作。

在MainActivity的onCreate方法中,我調用averageFragment = (AverageFragment) getSupportFragmentManager().findFragmentByTag(AverageFragment.tag);,但是這給了我一個NullPointerException。

我已經嘗試以下解決方案(其中大部分是從本網站):

  • getSupportFragmentManager().findFragmentById(R.id.fragment_average)
  • getSupportFragmentManager().findFragmentByTag(AverageFragment.tag) < - 基本上是一個靜態變量,實例化時的片段創建。
  • mSectionsPageAdapter.getItem(1)

所有這些都讓我無論是NPE或IllegalStateException.FragmentNotAttachedToView。

其他相關代碼:

public class SectionsPagerAdapter extends FragmentPagerAdapter { 

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

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     switch (position) { 
      case 0: 
       return InspectionFragment.newInstance(position + 1); 
      case 1: 
       return AverageFragment.newInstance(position + 1); 
      case 2: 
       return RegulationsFragment.newInstance(position + 1); 
     } 
     return null; 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 3; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     Locale l = Locale.getDefault(); 
     switch (position) { 
      case 0: 
       return getString(R.string.title_section1).toUpperCase(l); 
      case 1: 
       return getString(R.string.title_section2).toUpperCase(l); 
      case 2: 
       return getString(R.string.title_section3).toUpperCase(l); 
     } 
     return null; 
    } 
} 

如何從主要活動訪問片段任何想法?

回答

0

檢查將適配器實例分配給尋呼機的位置。你得到的例外是指該片段尚未加載到視圖的是,這很可能是因爲你調用你的任務:

averageFragment = (AverageFragment) getSupportFragmentManager().findFragmentByTag(AverageFragment.tag); 
從onCreate()方法

。嘗試將此作業移至onResume(),它應確保您的片段已加載到視圖中並可通過supportFragmentManager進行訪問。在將活頁夾的適配器設置在活動的生命週期中之後,也要確保此分配發生。

+0

完美的作品!謝謝 :) – suushiemaniac 2014-10-11 01:05:00