一、布局文件
<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"
android:background="@drawable/ic_launcher"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/vp"
/>
</RelativeLayout>
二、代码
import java.util.ArrayList;
import android.media.Image;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ViewPager vp;
private ArrayList<ImageView> lists;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.vp);
int []img={R.drawable.pic1,R.drawable.pic2,R.drawable.pic3};
lists = new ArrayList<ImageView>();
// iv = new ImageView(this); 不能放到外面,报The specified child already
//has a parent.You must call removeView() on the the child's parent first
for (int i = 0; i < img.length; i++) {
ImageView iv = new ImageView(this);
iv.setBackgroundResource(img[i]);
lists.add(iv);
}
vp.setAdapter(new PagerAdapter() {
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView view = lists.get(position);
container.addView(view);
return view;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0==arg1;
}
@Override
public int getCount() {
return lists.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
container.removeView((View) object);
}
});
}
}
3、效果图
代码:http://download.csdn.net/detail/gj_user/9832550