您的位置:首页 > 其它

ViewPager的简单实现

2014-02-26 10:52 253 查看
MainActivity:

private ViewPager pager_splash_ad;

private pageAdapter adapter;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

pager_splash_ad = (ViewPager) findViewById(R.id.pager_splash_ad);

List<View> views = new ArrayList<View>();

View view = LayoutInflater.from(this).inflate(

R.layout.pagecell, null);

ImageView iv_ad = (ImageView) view.findViewById(R.id.iv_ad);

iv_ad.setImageResource(R.drawable.tt);

views.add(view);

View view1 = LayoutInflater.from(this).inflate(

R.layout.pagecell, null);

ImageView iv_ad1 = (ImageView) view1.findViewById(R.id.iv_ad);

iv_ad1.setImageResource(R.drawable.ww);

views.add(view1);

View view2 = LayoutInflater.from(this).inflate(

R.layout.pagecell, null);

ImageView iv_ad2 = (ImageView) view2.findViewById(R.id.iv_ad);

iv_ad2.setImageResource(R.drawable.jj);

views.add(view2);

adapter = new pageAdapter(views);

pager_splash_ad.setAdapter(adapter);

}

MainActivity layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res/com.example.pagerdemo"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<FrameLayout

android:layout_width="match_parent"

android:layout_height="match_parent" >

<android.support.v4.view.ViewPager

android:id="@+id/pager_splash_ad"

android:layout_width="match_parent"

android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>

</FrameLayout>

</LinearLayout>

pagecell layout

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<ImageView

android:id="@+id/iv_ad"

android:layout_width="match_parent"

android:layout_height="match_parent" />

</LinearLayout>

PagerAdapter class:

public class pageAdapter extends PagerAdapter {

private List<View> mListViews;

public pageAdapter(List<View> mListViews){

this.mListViews = mListViews;

}

@Override

public int getCount() {

// TODO Auto-generated method stub

return mListViews == null ? 0 : mListViews.size();

}

@Override

public boolean isViewFromObject(View arg0, Object arg1) {

// TODO Auto-generated method stub

return arg0==arg1;//官方提示这样写

}

public void destroyItem(ViewGroup container,int position,Object object){

container.removeView(mListViews.get(position));

}

public Object instantiateItem(ViewGroup container,int position){

container.addView(mListViews.get(position), 0);

return mListViews.get(position);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: