viewpager.setpagerMargin();
代碼
public class MainActivity extends AppCompatActivity {
ViewPager vp;
int colors[]=new int[]{Color.BLACK,Color.BLUE,Color.GRAY,Color.GREEN,Color.RED};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp= (ViewPager) findViewById(R.id.vp);
vp.setPageMargin(30);//設置間距
vp.setOffscreenPageLimit(3);
vp.setAdapter(new Adapter());
}
class Adapter extends PagerAdapter{
@Override
public int getCount() {
return colors.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView=new ImageView(MainActivity.this);
imageView.setBackgroundColor(colors[position]);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
tools:context="com.example.administrator.myviewpager.MainActivity">
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="40dp"
android:clipChildren="false"
android:layout_centerHorizontal="true"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>