2015-11-06 84 views
0

我想從活動中創建FragmentPagerAdapter適配器。我如何做到這一點?從活動中調用FragmentPagerAdapter

當我從一個片段調用,但現在我想從一個活動中使用這種方式。

MyActivity.java

 // here error 
      adapter = new FragmentPagerAdapter(getFragmentManager(), 
        images.getImageItem()); 
      viewPage.setAdapter(adapter); 
      viewPage.setOnPageChangeListener(this); 

FragmentPagerAdapter.java

public class FragmentPagerAdapter extends FragmentStatePagerAdapter { 

private ArrayList<String> itemData; 

public FragmentPagerAdapter(FragmentManager fm, 
     ArrayList<String> itemData) { 
    super(fm); 
    this.itemData = itemData; 
} 
@Override 
public int getCount() { 
    return itemData.size(); 
} 
@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    super.destroyItem(container, position, object); 
} 
@Override 
public Fragment getItem(int position) { 
    FragmentImageView f = FragmentImageView.newInstance(); 
    f.setImageList(itemData.get(position)); 
    return f; 
} 
} 
+1

什麼是錯誤? – Kartheek

+0

@Kartheek構造函數FragmentPagerAdapter(FragmentManager,ArrayList )未定義 –

回答

1

更換

adapter = new FragmentPagerAdapter(getFragmentManager(),images.getImageItem()); 

adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 
       images.getImageItem()); 

getSupportFragmentManagerFragmentActivity方法,不屬於Activity,讓您的活動類必須實現FragmentActivity .Notice,你應該導入包com.support.v4.app.FragmentManager,不android.app.FragmentManager

+0

太棒了!解決了我的問題。非常感謝 –

1

而不是getFragmentManager呼叫getSupportFragmentManager

/** 
    * Return the FragmentManager for interacting with fragments associated 
    * with this activity. 
    */ 
    public FragmentManager getSupportFragmentManager() { 
     return mFragments.getSupportFragmentManager(); 
    } 

所以,你的代碼將

adapter = new FragmentPagerAdapter(getSupportFragmentManager(), 
        images.getImageItem()); 
      viewPage.setAdapter(adapter); 
      viewPage.setOnPageChangeListener(this); 
+0

只要調用getFragmentManager,第一個區域就是android源代碼。 – starkshang

+0

@FireSun不工作,因爲我不在片段 –

+0

@MadhukarHebbar \t 感謝您的快速重播,從哪裏我將得到變量mFragments? –