2015年4月28日 星期二
ViewPager with Fragment
public class CollectionOfItems extends FragmentActivity {
private List<Fragment> fragments;
.
.
略
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collectionofitems);
InitImageView();//初始化標頭並對它設定click偵聽和編號0.1.2
textView1 = (TextView) findViewById(R.id.text1);
.
.
略
textView1.setOnClickListener(new MyOnClickListener(0));
.
.
略
fragments = new ArrayList<Fragment>();
viewPager = (ViewPager) findViewById(R.id.viewPager); //取得viewPager資源
Fragment f1 = new Fragment1();
Fragment f2 = new Fragment2();
.
.
fragments.add(f1);
fragments.add(f2);
.
.
fragmentAdapter fa = new fragmentAdapter(getSupportFragmentManager(),fragments);
viewPager.setAdapter(fa);
viewPager.setCurrentItem(0);//頁卡預設為第一頁
viewPager.setOnPageChangeListener(new MyOnPageChangeListener());
}
//實現FragmentPagerAdapter
public class fragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
private FragmentManager fm;
public fragmentAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
public fragmentAdapter(FragmentManager fm) {
super(fm);
this.fm = fm;
}
@Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
@Override
public int getCount() {
return fragments.size();
}
}
-------------------------------------------------------------------------------------------------
Fragment1.java
public class Fragment1 extends Fragment{
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment1, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
.
.
要執行的程式
.
.
.
}
-----------------------------------------------------------------------------------------------
fragment1.xml
隨意..