ViewPager,它是google SDk中自带的一个附加包的一个类, 可以使视图滑动。
步骤:
1、引入android-support-v4.jar包,在主布局里加入
<android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="wrap_content" > </android.support.v4.view.ViewPager>
2、加载切换内容
3、ViewPager加载适配器PagerAdapter
public class MainActivity extends Activity { private ViewPager viewPager; private ArrayList<View> pageview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //设置无标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); viewPager = (ViewPager) findViewById(R.id.viewPager); //查找布局文件用LayoutInflater.inflate LayoutInflater inflater =getLayoutInflater(); View view1 = inflater.inflate(R.layout.item01, null); View view2 = inflater.inflate(R.layout.item02, null); View view3 = inflater.inflate(R.layout.item03, null); //将view装入数组 pageview =new ArrayList<View>(); pageview.add(view1); pageview.add(view2); pageview.add(view3); //数据适配器 PagerAdapter mPagerAdapter = new PagerAdapter(){ @Override //获取当前窗体界面数 public int getCount() { // TODO Auto-generated method stub return pageview.size(); } @Override //断是否由对象生成界面 public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0==arg1; } //是从ViewGroup中移出当前View public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView(pageview.get(arg1)); } //返回一个对象,这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中 public Object instantiateItem(View arg0, int arg1){ ((ViewPager)arg0).addView(pageview.get(arg1)); return pageview.get(arg1); } }; //绑定适配器 viewPager.setAdapter(mPagerAdapter); } }
Android:使用ViewPager实现左右滑动切换图片 (简单版)
时间: 2024-10-13 21:30:01