我的android viewpager幻灯片显示有问题。我希望在最短时间后显示viewpager布局。这是我的代码示例。 我的主要班级:
public class MainActivity extends Activity {
private ViewPager mViewPager;
private SwipeAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
// set the adapter
adapter = new SwipeAdapter(MainActivity.this);
mViewPager.setAdapter(adapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
}
我的适配器类:
public class SwipeAdapter extends PagerAdapter {
private LayoutInflater mInflater;
private static int[] mLayouts = { R.layout.view_layout1,
R.layout.view_layout2, R.layout.view_layout3, R.layout.view_layout4 };
SwipeAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ViewGroup pageView = (ViewGroup) mInflater.inflate(mLayouts[position],
container, false);
container.addView(pageView);
getItemPosition(pageView);
return pageView;
}
@Override
public int getCount() {
return mLayouts.length;
}
@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
}
假设我想让viewpager布局在10秒后自动滑动。怎么可能呢。
答案 0 :(得分:29)
使用Handler自动滑动。这是一些代码
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
if( position >= 4){
position = 0;
}else{
position = position+1;
}
toBarPager.setCurrentItem(position, true);
handler.postDelayed(runnable, 10000);
}
};
并且不要忘记删除回调onPause()
@Override
public void onPause() {
super.onPause();
if (handler!= null) {
handler.removeCallbacks(runnable);
}
}
另外,请勿忘记重新运行onResume()
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
handler.postDelayed(runnable, 10000);
}
答案 1 :(得分:1)
使用Handler并发送[Empty] MessageDelayed / postDelayed并在ViewPager上调用setCurrentItem