一、效果图
轮播.png是定时自动切换的,没弄gif,大家懂就行
二、思路
上方用viewpager,下面用LinearLayout动态添加view,view设置setBackgroundResource。然后用RxJava做间隔时间循环操作vp的setCurrentItem,然后vp的onPageSelected来控制LinearLayout里的view那个选中。这样就转起来了
三、案例关键代码
1.view的background
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true">
<shape android:shape="oval">
<solid android:color="@color/c_f44336"/>
</shape>
</item>
<item
android:state_selected="false">
<shape android:shape="oval">
<solid android:color="@color/c_bd"/>
</shape>
</item>
</selector>
2.整体代码
initPoint(fragments.size,llRecommendActivePoints!!)
if (fragments.size > 1) {
startLoopRecommend(fragments.size)
}
vpRecommendActive?.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(p0: Int) {
}
override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
}
override fun onPageSelected(pos: Int) {
var i = 0
if(llRecommendActivePoints != null){
while (i< llRecommendActivePoints!!.childCount){
llRecommendActivePoints!!.getChildAt(i).isSelected = false
i++
}
}
llRecommendActivePoints?.getChildAt(pos)?.isSelected = true
}
})
其中:
private fun initPoint(pointSize: Int, ll: LinearLayout) {
ll.visibility = View.VISIBLE
ll.removeAllViews()
for (i in 0 until pointSize) {
//小指标点
val vPoint = View(context)
vPoint.setBackgroundResource(R.drawable.active_recommed_point_selector)
vPoint.isSelected = false
val params = LinearLayout.LayoutParams(
UtilHelper.dip2px(context, 8f),
UtilHelper.dip2px(context, 8f))
if (i != 0) params.leftMargin = UtilHelper.dip2px(context, 8f)
vPoint.layoutParams = params
ll.addView(vPoint)
}
if (ll.childCount > 0) {
ll.getChildAt(0).isSelected = true
}
}
private fun startLoopRecommend(size:Int){
if (subscription == null){
subscription = Observable.interval(4,TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Consumer {
if (vpRecommendActive != null){
var mCurrentItem = vpRecommendActive!!.currentItem
if (mCurrentItem == size - 1) {
mCurrentItem = 0
} else {
mCurrentItem++
}
vpRecommendActive!!.currentItem = mCurrentItem
}
})
}
}
好了,关键是LinearLayout里面的点生成和控制,喜欢的点个赞
网友评论