android ViewPager左右滑动翻页,并可以删除page
首先新建一个Activity,继承FragmentActivity。
初始化一个Fragment的List集合,用于像FragmentStatePagerAdapter填充数据,而ViewPager由FragmentStatePagerAdapter的实例进行初始化。和ListView一样,Fragment的List集合的数据变了,就通知FragmentStatePagerAdapter进行界面刷新。
ArrayList<Fragment> fragments =new ArrayList<Fragment>();
Fragment fragment1 = newFragment();
Fragment fragment2 = newFragment();
fragments.add(mediaFragment1);
fragments.add(mediaFragment2);
TheMediaAdapter theAdapter = new TheMediaAdapter(getSupportFragmentManager(),fragments);
viewpager.setAdapter(theAdapter);
删除一项时:
fragments.remove(index);
theAdapter.notifyDataSetChanged();
TheMediaAdapter类:
import java.util.ArrayList;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import com.henizaiyiqi.doctorassistant.view.MediaFragment;
//一定要继承FragmentStatePagerAdapter,而不是FragmentPagerAdapter,不然删除PageView中的一项后显示的还是之前内存的页。
public class TheMediaAdapter extends FragmentStatePagerAdapter {
private ArrayList<MediaFragment>fragments;
private FragmentManager fm;
public TheMediaAdapter(FragmentManager fm,ArrayList<MediaFragment>fragments) {
super(fm);
this.fm = fm;
this.fragments=fragments;
}
@Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return fragments.size();
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public void setFragments(ArrayList fragments) {
if(this.fragments != null){
FragmentTransaction ft = fm.beginTransaction();
for(Fragment f:this.fragments){
ft.remove(f);
}
ft.commit();
ft=null;
fm.executePendingTransactions();
}
this.fragments = fragments;
notifyDataSetChanged();
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。