之前觉得滑动翻页的效果挺炫的,目前初学android,所以自己在项目中尝试实现了这个效果。数据是动态的。实现效果主要有几个步骤:
1、创建两个布局文件,一个布局文件定义viewPager组件,如 <android.support.v4.view.ViewPager
android:id="@+id/vp_articles"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</android.support.v4.view.ViewPager >;另外一个布局文件定义在viewPager中要展示的View,因为有点复杂,代码就不贴了
2、创建一个activity管理viewPager,主要的java代码有:
public class ActivityArticleTest extends BaseActivity {
private ViewPager viewPager = null; //定义viewPager
private LayoutInflater mInflater = null; //加载布局文件用
private ArrayList<View> viewsList = null; //用arraylist 存储要展现的view
protected void onCreate(Bundle arg0) {
viewPager = (ViewPager) findViewById(R.id.vp_articles);
mInflater = LayoutInflater.from(this);
viewsList = new ArrayList<View>();
//作为一个例子 往viewList添加View
for(int j =0 ; j<idslist.size();j++){
View view = mInflater.inflate(R.layout.activity_resumption_article, null);
viewsList.add(view);
//给viewPager添加适配器,也可继承PagerAdapter
viewPager.setAdapter(new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return viewsList.size();
}
@Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return viewsList.indexOf(object);
}
//这个方法和下面这个方法慢重要的
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(viewsList.get(position));
return viewsList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position,
Object object) {
// TODO Auto-generated method stub
container.removeView(viewsList.get(position));
}
});
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
//重新发起请求,更新所在view
getDataFromRepreWeb(method, idslist.get(arg0));
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
}); }
}
模式简单,重要的是和项目的业务结合
ViewPager实现翻页步骤,布布扣,bubuko.com