Android开发中ViewPager实现多页面切换效果

ViewPager用于实现多页面的切换效果,该类存在于Google的兼容包里面,所以在引用时记得在BuilldPath中加入“Android-support-v4.jar”

首先必须知道:要使用ViewPager,必须要使用PagerAdapter为其提供数据,也就必须实现下面四个方法:

1, getCount():ViewPager需要显示的页面个数

2,isViewFromObject(View view, Object object):view 是某个位置的页面,Object是 instantiateItem 方法返回的。在这个方法需要判断这页面与Object对象是

否是同一个对象。

3,instantiateItem(ViewGroup Container, int position):生成对应位置的页面,container 就是显示页面的容器,position 就是对应的页面的序号

4,destroyItem(ViewGroup container, int position, Object object):将指定页面销毁

其实现代码”如下”:

1,直接在布局文件中引入ViewPager

注意:必须要导入其依赖包android.support.v4

<android.support.v4.view.ViewPager
android:id="@+id/up"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>

2,自定义一个适配器继承于PagerAdapter,并覆写其四个方法

public class MyPagerAdapter extends PagerAdapter {
private Context mContext;
private int[] mResId;
public MyPagerAdapter(Context context, int[] resId) {
this.mContext = context;
this.mResId = resId;
}
//设置内部pager页面的数量
@Override
public int getCount() {
return mResId.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
//判断页面与object是否是同一个对象
return view == object;
}
//必须重新覆写instaniateItem()和destroyItem()二个方法才能进行展示
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = View.inflate(mContext, R.layout.item, null);
View iv_item = view.findViewById(R.id.iv_item);
iv_item.setBackgroundResource(mResId[position]);
//必须将填充出来的view添加到ViewGroup中去,其container表示当前页面的容器
container.addView(view);
return view;
}
//不使用的时候,将其销毁
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//父类实现的方法是抛异常(源码)
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
}

3,activity中实现其逻辑

public class MainActivity extends Activity {
private ViewPager mUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initeView();
initData();
}
private void initData() {
int[] resId = new int[]{R.drawable.shi, R.drawable.ni, R.drawable.haha};
//给ViewPager设置内容
MyPagerAdapter adapter = new MyPagerAdapter(getApplicationContext(), resId);
mUp.setAdapter(adapter);
}
private void initeView() {
mUp = (ViewPager) findViewById(R.id.up);
}
}

以上所述是小编给大家介绍的Android开发中ViewPager实现多页面切换效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对呐喊教程网站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。