Android ViewPager实现左右滑动翻页效果

2020-10-28 20:03:07 浏览数 (1)

本文实例为大家分享了ViewPager实现左右滑动翻页效果展示的具体代码,供大家参考,具体内容如下

代码如下:

代码语言:javascript复制
package com.example.demo; 
 
import java.util.ArrayList; 
 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.support.v4.view.PagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 
 
 
public class MainActivity extends Activity { 
 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
   
  ViewPager mViewPager=(ViewPager) findViewById(R.id.viewPager); 
   
  PagerAdapter mPagerAdapter=new MyPagerAdapter(this); 
   
  mViewPager.setAdapter(mPagerAdapter); 
 } 
  
 private class MyPagerAdapter extends PagerAdapter{ 
 
  private Context context; 
   
  private ArrayList<TextView  views; 
   
  public MyPagerAdapter(Context context){ 
   this.context=context; 
   views=new ArrayList<TextView (); 
   for(int i=0;i<30;i  ){ 
    TextView tv=new TextView(context); 
    tv.setText("" i); 
    views.add(tv); 
   } 
  } 
   
  @Override 
  public int getCount() { 
   return views.size(); 
  } 
   
  @Override 
  public void destroyItem(ViewGroup container, int position,Object object) { 
   container.removeView(views.get(position)); 
  } 
   
  @Override 
  public View instantiateItem(ViewGroup container, int position){ 
    ((ViewGroup) container).addView(views.get(position)); 
    
   return views.get(position); 
  } 
 
  @Override 
  public boolean isViewFromObject(View arg0, Object arg1) { 
   return arg0==arg1; 
  } 
 } 
} 

布局文件:

代码语言:javascript复制
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 tools:context="com.example.demo.MainActivity"   
 
 <android.support.v4.view.ViewPager 
  android:id="@ id/viewPager" 
  android:layout_width="match_parent" 
 android:layout_height="match_parent"/  
</RelativeLayout  

以上就是本文的全部内容,希望对大家的学习有所帮助。

0 人点赞