ViewPager + Fragment的使用此处不写,网上太多了。主要放在循环滚动、indicator 和 定时滚动上
1.indicator的实现
首先定义indicator,使用FrameLayout让指示的原点悬浮在viewpager 上。
<FrameLayout android:layout_width="fill_parent" android:layout_height="144dp"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="@+id/focus_pager"
android:layout_alignParentTop="true"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|bottom"
android:gravity="center"
android:id="@+id/online_pager_indicaor"
android:paddingBottom="5dp"
android:alpha="0.3"
android:background="@color/black"
></LinearLayout>
</FrameLayout>
初始化indicator 加入 online_pager_indicator中
for (int i = 0; i < count; i++ ){
Log.d(TAG, "initViewPagerIndicator i :" + i);
img[i] = new ImageView(this);
if (i == mViewPager.getCurrentItem()){
img[i].setImageResource(R.drawable.indicator_focused);
}else {
img[i].setImageResource(R.drawable.indicator_normal);
}
img[i].setPadding(0, (int) (5*density), (int) (10*density), 0);
indicatorlayout.addView(img[i]);
}
设置Viewager的滑动监听
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int i) {
//这种方法有时不生效,不行的话只有一个一个设置图片了。。。
/*for (int index = 0; index < 5; index++){
Log.d(TAG, "onPageSelected index :" + index);
if (i == index){
img[i].setImageResource((R.drawable.indicator_focused));
}else {
img[i].setImageResource((R.drawable.indicator_normal));
}
}*/
实现完毕。
2.循环滚动
在FragmentPagerAdapter中
mCount = mOnlineFocusFragmentList.size();
@Override
public Fragment getItem(int i) {
if (i >= mOnlineFocusFragmentList.size()){
int newposition = i%mOnlineFocusFragmentList.size();
i = newposition;
}
if (i < 0 ){
i = -i;
}
Log.d(TAG,"getItem :" + mOnlineFocusFragmentList.get(i));
return mOnlineFocusFragmentList == null ? null :mOnlineFocusFragmentList.get(i);
// return (Fragment)new onlineFocusFragment();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (position >= mOnlineFocusFragmentList.size()){
int newposition = position%mOnlineFocusFragmentList.size();
position = newposition;
}
if (position < 0 ){
position = -position;
}
super.destroyItem(container, position, object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
if (position >= mOnlineFocusFragmentList.size()){
int newposition = position%mOnlineFocusFragmentList.size();
mCount++;
position = newposition;
}
if (position < 0 ){
position = -position;
mCount--;
}
return super.instantiateItem(container, position);
}
@Override
public int getCount() {
return mOnlineFocusFragmentList == null ? 0 : mCount + 1;
}
最后在滑动监听中给position 取余
@Override
public void onPageSelected(int i) {
if (i >= 5)
i = i%5;
if (i < 0)
i = -i;
}
OK
3.定时用 timerTask + Timer + Handler 实现
viewpager。setcurrentItem(index ++)