0

我正在尝试创建一个包含几个页面的viewpager,问题是所有页面看起来都一样(只是数据不同)所以我创建了一个片段类,我正在尝试添加同一个类的viewpager适配器实例......但我不能......

如何使每个页面都是同一片段类的实例的 viewpager?含义:相同的设计 - 不同的数据

编辑... 我从这里获取了一般代码... http://tamsler.blogspot.co.il/2011/10/android-viewpager-and-fragments.html

稍微扭了一下

public class MainActivity extends FragmentActivity {

private com.example.trying1.PagerAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initPaging();
}

private void initPaging() {
    List<Fragment> fragments = new ArrayList<Fragment>();
    NoteFragment nf = new NoteFragment();
    Bundle bundle = new Bundle();
    bundle.putString("noteTitle", "A");
    nf.setArguments(bundle);

    NoteFragment nf1 = new NoteFragment();
    Bundle bundle1 = new Bundle();
    bundle1.putString("noteTitle", "B");
    nf1.setArguments(bundle1);

    fragments.add(nf);
    fragments.add(nf1);
    this.mAdapter = new com.example.trying1.PagerAdapter(
            getSupportFragmentManager(), fragments);

    ViewPager vPager = (ViewPager) findViewById(R.id.pager);
    vPager.setAdapter(this.mAdapter);
}

}

4

1 回答 1

-1

当然可以。您是否收到错误或数据未更新?

编辑:

它还取决于您如何编码片段,接受作为参数并计算页面?

public class MainActivity extends FragmentActivity {

private MyFragmentPagerAdapter mAdapter;    
private List<Fragment> fragments;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initPaging();
}

private void initPaging() {
    fragments = new ArrayList<Fragment>();
    this.mAdapter = MyFragmentPagerAdapter(
            getSupportFragmentManager());
    ViewPager vPager = (ViewPager) findViewById(R.id.pager);

    //Add 3 fragments
     for(int i =0; i<3; i++)
       addFragments(i);

    //Set adapter     
     vPager.setAdapter(this.mAdapter);
}

 private void addFragments(int i){
   NoteFragment nf = new NoteFragment(i); //Pass data to the fragment, so it can process it
   //You may pass it as a bundle if you wish
   fragments.add(nf)
}    

//适配器代码

private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {  

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

           @Override  
           public Fragment getItem(int index) {     
                return fragments.get(index);
           }  

           @Override  
           public int getCount() {     
                return fragments.size();  
           }  
      }  

}
于 2012-07-26T18:06:01.027 回答