我在Android应用程序中创建了一个带有3个标签项的标签控件。
<android.support.design.widget.TabLayout
android:background="@color/colorPrimary"
android:layout_alignParentTop="true"
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="30dp"
>
</android.support.design.widget.TabLayout>
在PagerAdapter
的帮助下,其正常工作正常。但现在,我想自动制作它。也就是说,每隔5秒钟,标签应自动滑动到下一个标签。它将继续向用户触摸屏幕。如何在我的应用程序中添加此计时功能?
我的PagerAdapter
课程是,
public class PagerAdapter extends FragmentStatePagerAdapter{
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment frag=null;
switch (position){
case 0:
frag=new GameFragment();
break;
case 1:
frag=new MovieFragment();
break;
case 2:
frag=new StudyFragment();
break;
}
return frag;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
String title=" ";
switch (position){
case 0:
title="Game";
break;
case 1:
title="Movie";
break;
case 2:
title="Study";
break;
}
return title;
}
}
答案 0 :(得分:5)
您可以执行以下操作来自动滑动标签:
int NUM_PAGES = 3;
int currentPage = 0;
boolean touched = false;
Handler handler = new Handler();
Runnable update;
private void startPagerAutoSwipe() {
update = new Runnable() {
public void run() {
if(!touched){
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
pager.setCurrentItem(currentPage++, true);
}
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(update);
}
}, 5000, 5000);
}
要点击其中一个片段时停止自动滑动,您可以使用onTouchListener
进行布局:
layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touched = true;
return true;
case MotionEvent.ACTION_UP:
touched = false;
return true;
}
return false;
}
});