直接代码:后面附上压缩文件:
package cn.kevin.test.matrixtest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements OnPageChangeListener {
private ViewPager viewPager;
private int[] idArray;// 图片
private ImageView[] tips;// 点点的图片
private ImageView[] mImages;// 放图片的数组
private LinearLayout radio;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
radio = (LinearLayout) findViewById(R.id.radio);
idArray = new int[] { R.drawable.a1, R.drawable.a2, R.drawable.a3,
R.drawable.a4, R.drawable.a5 };
tips = new ImageView[idArray.length];
for (int i = 0; i < tips.length; i++) {
ImageView image = new ImageView(MainActivity.this);
tips[i] = image;
if (i == 0) {
tips[i].setBackgroundResource(R.drawable.image_select);
} else {
tips[i].setBackgroundResource(R.drawable.image);
}
radio.addView(image);
image.setPadding(10, 10, 10, 10);
radio.setGravity(Gravity.CENTER);
radio.setOrientation(0);
}
mImages = new ImageView[tips.length];
for (int i = 0; i < mImages.length; i++) {
ImageView mImage = new ImageView(MainActivity.this);
mImages[i] = mImage;
mImage.setBackgroundResource(idArray[i]);
}
viewPager.setAdapter(new MyAdapter());
viewPager.setOnPageChangeListener(this);
// 设置ViewPager的默认项, 设置为长度的100倍,这样子开始就能往左滑动
// viewPager.setCurrentItem((mImages.length) * 100);
}
public class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(mImages[position % mImages.length]);
}
@Override
public Object instantiateItem(View container, int position) {
((ViewPager) container).addView(mImages[position % mImages.length],
0);
return mImages[position % mImages.length];
}
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
setImageBackGround(arg0 % mImages.length);
}
public void setImageBackGround(int selectItem) {
for (int i = 0; i < tips.length; i++) {
if (i == selectItem) {
tips[i].setBackgroundResource(R.drawable.image_select);
} else {
tips[i].setBackgroundResource(R.drawable.image);
}
}
}
}