我想做个ViewPager自动轮播,遇到一些问题,大家能帮忙看下不
就是在设置好xiewpager之后我再MainActivity中像老师那样建立一个内部类,实现接口Runnable
就是在设置好xiewpager之后我再MainActivity中像老师那样建立一个内部类,实现接口Runnable
2016-09-11
package com.example.nete.viewpager; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import java.util.List; public class Mypager extends PagerAdapter { public List<View> listview; public Mypager(List<View> datas) { listview = datas; } @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) { int mposition = position % listview.size(); container.addView(listview.get(mposition)); return listview.get(mposition); } @Override//销毁一个页卡,去掉super public void destroyItem(ViewGroup container, int position, Object object) { int mposition = position % listview.size(); container.removeView(listview.get(mposition)); } }
package com.example.nete.viewpager; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public ViewPager viewpager; private List<View> listView; public Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.viewpager_main); viewpager = (ViewPager) findViewById(R.id.viewpager); listView = new ArrayList<View>();//初始化该列表 //加载四个布局 View view1 = View.inflate(this, R.layout.view1, null); View view2 = View.inflate(this, R.layout.view2, null); View view3 = View.inflate(this, R.layout.view3, null); View view4 = View.inflate(this, R.layout.view4, null); // 将四个布局加入list中 listView.add(view1); listView.add(view2); listView.add(view3); listView.add(view4); Mypager adapter = new Mypager(listView); viewpager.setAdapter(adapter); handler.postDelayed(new MyRunnable(), 1500); } class MyRunnable implements Runnable { int index = 0; @Override public void run() { index %= 4; viewpager.setCurrentItem(index); handler.postDelayed(new MyRunnable(), 1500); index++; } } }
举报