欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

viewpager循环拖动

程序员文章站 2022-06-09 15:56:42
...
最近在研究viewpager,准备做循环拖动即A->B->C->A->B->C->A->...
找了一下相关资料,只有stactoverflow上有一条比较靠谱的资料,但是不全,自己琢磨了一下,实现了循环拖动。

这里只需要对pageadapter进行操作,源代码如下:

public class ViewPagerAdapter extends PagerAdapter{

private List<View> views;
Context context;
int mCount;
public ViewPagerAdapter(Context context,List<View> views){
this.views=views;
this.context=context;
mCount = views.size() +1;
}
@Override
public void destroyItem(View collection, int position, Object arg2) {
if (position >= views.size()-1) {
int newPosition = position%views.size();
position = newPosition;
((ViewPager) collection).removeView(views.get(position));
}
}

@Override
public void finishUpdate(View arg0) {

}

@Override
public int getCount() {
return mCount;
}

@Override
public Object instantiateItem(View collection, int position) {

if (position >= views.size()-1) {
int newPosition = position%views.size();

position = newPosition;
mCount++;
}

try {
((ViewPager) collection).addView(views.get(position),0);
} catch (Exception e) {
}
return views.get(position);
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view==(object);
}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {

}

@Override
public Parcelable saveState() {
return null;
}

@Override
public void startUpdate(View arg0) {

}

}



再附上Activity的源码:

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;

public class ViewPageDemoActivity extends Activity {

ViewPager pager;
LayoutInflater inflater;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pager=(ViewPager) this.findViewById(R.id.view_pager);
inflater=LayoutInflater.from(this);
List<View> views=new ArrayList<View>();
View view1=inflater.inflate(R.layout.layout1, null);
View view2=inflater.inflate(R.layout.layout2, null);
View view3=inflater.inflate(R.layout.layout3, null);
Views.add(view1);
Views.add(view2);
Views.add(view3);

ViewPagAdapter adapter=new ViewPagAdapter(this, views);
pager.setAdapter(adapter);

}
}
相关标签: viewpager