显示页面
package com.bw.uigaoji.fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.bw.uigaoji.R; import com.bw.uigaoji.adapter.ViewPagerAdapter; import com.google.gson.Gson; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class F1 extends Fragment { private View view; private ViewPager mVp; private ListView mList; //代表那个图片图片 int i=0; //数据源 int[] ints={R.drawable.j1,R.drawable.j2,R.drawable.j3,R.drawable.j4,R.drawable.j5,R.drawable.j6}; //切换图片 Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); //设置vp显示视图位置 mVp.setCurrentItem(i); i++; } }; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.f1_item, container, false); initView(view); mVp.setOffscreenPageLimit(4); Timer timer=new Timer(); //让定时器执行任务, 每一秒发一次信息; timer.schedule(new TimerTask() { @Override public void run() { handler.sendEmptyMessage(0); } },0,1000); ViewPagerAdapter viewPagerAdapter=new ViewPagerAdapter(getActivity(),ints); mVp.setAdapter(viewPagerAdapter); Gson gson=new Gson(); return view; } private void initView(View view) { mVp = (ViewPager) view.findViewById(R.id.vp); mList = (ListView) view.findViewById(R.id.list); } }
适配器
package com.bw.uigaoji.adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; //继承PagerAdapter会重写两个方法 但是还要自己手动重写两个方法分别是instantiateItem和destroyItem public class ViewPagerAdapter extends PagerAdapter { Context context; int[] ints; public ViewPagerAdapter(Context context, int[] ints) { this.context = context; this.ints = ints; } @Override public int getCount() { //最大值 return Integer.MAX_VALUE; } @Override public boolean isViewFromObject(View view, Object object) { //相等于 return view==object; } //重写第一个的方法 @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView=new ImageView(context); //下标为几的图抹除于数组长度 imageView.setImageResource(ints[position%ints.length]); //拉伸图片 imageView.setScaleType(ImageView.ScaleType.FIT_XY); //添加 container.addView(imageView); return imageView; } //重写的第二个方法 @Override public void destroyItem(ViewGroup container, int position, Object object) { //注释掉就可以了 //super.destroyItem(container, position, object); //remove强转 container.removeView((View) object); } }