【领券联盟】笔记:视频51,52-实现首页的轮播功能
破小布的小花狗
发表于
2020-04-03 06:22
1531
课堂笔记
课堂笔记
- 创建 AutoLooperViewPager 继承 ViewPager 替换我们之前的布局 LooperViewPager
public class AutoLooperViewPager extends ViewPager {
public AutoLooperViewPager(@NonNull Context context) {
super(context);
}
public AutoLooperViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
}
- 在 AutoLooperViewPager 中写两个方法,分别控制轮播图的开始和停止
private boolean isLooper = false;
//开始轮转
public void startLoop() {
isLooper = true;
post(task);
}
//停止轮转
public void stopLoop() {
removeCallbacks(task);
isLooper = false;
}
private Runnable task = new Runnable() {
@Override
public void run() {
int currentItem = getCurrentItem();
currentItem++;
setCurrentItem(currentItem);
if (isLooper) {
postDelayed(this, duration);
}
}
};
- duration 有个默认值
private static final int DEFAULT_DELAY = 2000;
private int duration = DEFAULT_DELAY;
- 在 HomePagerFragment 的 onResume 和 onPause 方法中分别调用 startLoop() 和 stopLoop() 方法,让轮播图随着界面的是否可见而开始和停止
@Override
public void onResume() {
super.onResume();
looperPager.startLoop();
}
@Override
public void onPause() {
super.onPause();
looperPager.stopLoop();
}
- 接下来我们要在 < resources > 下为轮转间隔自定义属性
<resources>
<declare-styleable name="AutoLooperStyle" >
<attr name="duration" format="integer" />
</declare-styleable>
</resources>
- 找到属性
public AutoLooperViewPager(@NonNull Context context) {
this(context, null);
}
public AutoLooperViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoLooperStyle);
duration = typedArray.getInteger(R.styleable.AutoLooperStyle_duration, DEFAULT_DELAY);
typedArray.recycle();
}
- 这样我们就可以在布局中为属性赋值了
<com.xiaobu.taobaouni.ui.custom.AutoLooperViewPager
android:id="@+id/looper_pager"
android:layout_width="match_parent"
android:layout_height="125dp"
android:overScrollMode="never"
app:looperTimer="1500" />
- 也可以对外暴露一个设置轮播间隔的方法
public void setDuration(int duration){
this.duration = duration;
}
- 可以在开始轮播前调用设置时间
@Override
public void onResume() {
super.onResume();
looperPager.setDuration(800);
looperPager.startLoop();
}