桌面可活动View跟随Viewpager自动轮播,回到开端地方化解

支持无限循环,自动轮播,反转播放的ViewPagerAdapter

ionic4开发,切换页面后,停止自动轮播,这个怎么处理?
html代码如下:

问题:

一个实用的图片切换支持点击切换和自动轮播,切换点击轮播

不经意间看到了以前写的这个小东西,就贴上来了,支持点击切换和自动轮播,供前端新手看看吧!

代码如下:

<div class="scroll_div">
<ul class="pic">
<li><img src="img/pic_1.jpg" /></li>
<li><img src="img/pic_2.jpg" /></li>
<li><img src="img/pic_3.jpg" /></li>
<li><img src="img/pic_4.jpg" /></li>
<li><img src="img/pic_5.jpg" /></li>
</ul>
<ul class="btn">
<li>项目一</li>
<li>项目二</li>
<li>项目三</li>
<li>项目四</li>
<li>项目五</li>
</ul>
</div>

html

此处只需将图片路径改成你本地的即可。

.scroll_div{width:1000px; height:370px; margin:0 auto; padding:10px;}
.scroll_div .pic{width:820px; height:370px; overflow:hidden; position:relative; float:left;}
.scroll_div .pic li{width:820px; height:370px; position:absolute; top:0; left:0; display:none;}
.scroll_div .btn{float:right; width:173px;}
.scroll_div .btn li{width:173px; height:66px; display:block; float:left; text-align:center; color:#fff; font:18px/100% "微软雅黑"; font-weight:bold; background:#008dd8; margin-bottom:10px; line-height:66px; cursor:pointer;}
.scroll_div .btn li.on{background:#d73737;}

li {list-style:none;}

css

$(function(){
var listLen = $(".pic li").length, i=0,setInter,speen = 3000;
/*图片轮播*/
$(".btn li:last").css({"margin":"0px 0px 0px 0px"});
$(".btn li:first").addClass("on");
$(".pic li:first").show();

$(".btn li").each(function(index,element){
$(element).click(function(){
i = index;
$(this).addClass("on").siblings().removeClass("on");
$(".pic li").eq(index).animate({opacity:"show"},300).siblings().animate({opacity:"hide"},300);
})
$(element).hover(function(){
clearInterval(setInter);
},function(){
outPlay();
});
})


out_fun = function(){
if(i < listLen){i++;}else{i=0;};
$(".btn li").eq(i).addClass("on").siblings().removeClass("on");
$(".pic li").eq(i).animate({opacity:"show"},300).siblings().animate({opacity:"hide"},300);
}

outPlay = function(){
setInter = setInterval("out_fun()",speen);
}
outPlay();
})

触摸暂停切换

//图片 1
第一张图片

MainActivity  中通过Viewpager
管理了四个Fragment,需求是在第一个Fragment(HomeFragment)中放置

  使用bootstrap的轮播做图片幻灯片,发现轮播到最后一张的时候,显示不正常了。

网页图片轮播代码,三张图,鼠标点击右下角图片号码就切换,不点击则自动切换

<script language=”javascript”>
j=0;
function show(){
for(ii=1;ii<6;ii++)
{
document.getElementById(“pic”+ii).style.display=”none”;
document.getElementById(“Submit”+ii).style.backgroundColor=”;
}
j++
if(j==6){
j=1;
}
document.getElementById(“pic”+j).style.display=”block”;
document.getElementById(“Submit”+j).style.backgroundColor=’blue’;
a=setTimeout(‘show()’,1000);
}
function pic(pic){
clearTimeout(a);
for(var i=1;i<=5;i++){
if(i==pic){
document.getElementById(“pic”+pic).style.display=”block”;
document.getElementById(“Submit”+pic).style.backgroundColor=’blue’;
j=i
}else {
document.getElementById(“pic”+i).style.display=”none”;
document.getElementById(“Submit”+i).style.backgroundColor=”;
}
}
a=setTimeout(‘show()’,1000);
}
</script>
<style type=”text/css”>
input{ background-color:white; border:#FF0000
border: 0px;
margin: 0px;
padding: 0px;
height: 20px;
width: 20px;
font-size: 14px;}
</style>

<body onLoad=”show()”>
<table width=”461″ height=”163″>
<tr>
<td width=”426″ rowspan=”7″>
<img id=”pic3″ style=”display:none”src=”image/class1-2.jpg” >
<img id=”pic1″ src=&qu……余下全文>>
 

缩放pagertransformer

第二张图片

HomeFramgment中找到控件,这里是一个button,

 

javascript 图片切换轮播

模仿爱奇艺首页图片轮播:

HTML代码:

<!doctype html>
<html>
<head>
<meta charset=’utf-8’/>
<title>爱奇艺轮播图</title>
<link href=”index.css” rel=”stylesheet” type=”text/css” />
<script src=”move.js” type=”text/javascript”></script>
<script type=”text/javascript”>
window.onload = function (){
var
arr=[‘第1张’,’第2张’,’第3张’,’第4张’,’第5张’,’第6张’,’第7张’,’第8张’,’第9张’,’第10张’];
var domWidth = document.documentElement.clientWidth;
var aScrollLi = $(‘scroll_ul’).getElementsByTagName(‘li’);
var aThumbLi = $(‘thumb_ul’).getElementsByTagName(‘li’);
var timer = null;
var iNow=0;
for(var m=0; m<aScrollLi.length; m++){
aScrollLi[m].style.backgroundPosition =
-parseInt((1500-$(‘outline’).offsetWidth)/2)+’px,0px’;
}
window.onresize =function (){
for(var m=0; m<aScrollLi.length; m++){
aScrollLi[m].style.backgroundPosition =
-parseInt((1500-$(‘outline’).offsetWidth)/2)+’px,0px’;
}
}
for(var i=0; i&lt……余下全文>>
 

不经意间看到了以前写的这个小东西,就贴上来了,支持点击切换和自动轮播…

无限循环是利用反射设置一个很大的数值来无限循环

第三张图片

保存拖动过程的位置,在addOnLayoutChangeListener中重写设置,点击事件:保存按下的系统时间和抬起时系统时间,多少时间内算是点击事件。

原因:

效果

图片 2GIF.gifgithub地址图片 3GIF.gif

 LoopFragmentPagerAdapter adapter = new LoopFragmentPagerAdapter(getSupportFragmentManager { @Override public int getActualCount() { return 3; } @Override public Fragment getActualItem(int position) { return new MyFragment(); } @Override public CharSequence getActualPagerTitle(int position) { return "标题" + position; } }; adapter.setSwitchPeriod; //不循环 反转轮播 adapter.setLoop; //自动轮播 adapter.setAutoSwitch; viewPager.setAdapter;

/** * Created by 不听话的好孩子 on 2017/12/6. * <p> * 有RXjava用Rxjava实现切换,无Rxjava用post */public abstract class LoopFragmentPagerAdapter extends FragmentStatePagerAdapter { /** * 用来启动动画 设置循环 */ private boolean isfirst = true; /** * 触摸的时候停止切换 */ private boolean touched = false; /** * 切换间隔 */ private int switchPeriod = 5000; /** * 自动切换 */ private boolean autoSwitch = true; /** * 是否需要无限循环 */ private boolean loop = true; /** * post runnable */ private Runnable action; private int BIGCOUNT = 1000000; private Disposable disposable; private boolean reverse; /** * 有无rxjava */ private boolean hasRx; public LoopFragmentPagerAdapter(FragmentManager fm) { super; } @Override public Fragment getItem(int position) { return getActualItem(position % getActualCount; } @Override public void startUpdate(final ViewGroup container) { super.startUpdate(container); if  { isfirst = false; if  { try { doSettCurrenPager(container); } catch (Exception e) { e.printStackTrace(); } } if (autoSwitch) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { startLoop((ViewPager) container); } } } } /** * 反射设置一个很大的位置达到伪无限循环 * * @param container * @throws Exception */ private void doSettCurrenPager(ViewGroup container) throws Exception { Field mCurItem = ViewPager.class.getDeclaredField("mCurItem"); mCurItem.setAccessible; mCurItem.setInt(container, 1000000 - (BIGCOUNT % getActualCount; } @Override public CharSequence getPageTitle(int position) { return getActualPagerTitle(position % getActualCount; } @Override public int getCount() { return loop ? Integer.MAX_VALUE : getActualCount(); } /** * 执行循环切换 * * @param viewPager */ @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) private void startLoop(final ViewPager viewPager) { hasRx = checkIfHasRx(); Log.w("LoopFragmentPager", "startLoop: " + (hasRx ? "当前使用Rxjava" : "当前使用View.post"), null); if  { usePost(viewPager); } else { userRx(viewPager); } viewPager.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: if  { touched = true; if  { viewPager.removeCallbacks; } } break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: touched = false; if  { viewPager.postDelayed(action, switchPeriod); } break; } return false; } }); viewPager.getViewTreeObserver().addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListener() { @Override public void onWindowAttached() { } @Override public void onWindowDetached() { disposable.dispose(); viewPager.removeCallbacks; action = null; viewPager.getViewTreeObserver().removeOnWindowAttachListener; viewPager.setOnTouchListener; } }); } /** * 用Rxjava做循环切换 * * @param viewPager */ private void userRx(final ViewPager viewPager) { disposable = Observable.interval(switchPeriod, switchPeriod, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io .observeOn(AndroidSchedulers.mainThread .subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { if  { viewPager.setCurrentItem(caculatItem(viewPager)); } } }); } /** * 用View.post作循环切换 * * @param container */ @SuppressLint("ClickableViewAccessibility") private void usePost(final ViewPager container) { if (action == null) { action = new Runnable() { @Override public void run() { container.setCurrentItem(caculatItem(container)); container.postDelayed(this, switchPeriod); } }; } container.postDelayed(action, switchPeriod); } private int caculatItem(ViewPager viewPager){ int nextItem = !reverse ? (viewPager.getCurrentItem : (viewPager.getCurrentItem; if  { if (nextItem >= getActualCount { reverse = true; nextItem = viewPager.getCurrentItem() - 1; } if (nextItem < 0) { reverse = false; nextItem = 1; } } return nextItem; } /** * 是否含有Rxjava库 * * @return */ private boolean checkIfHasRx() { try { Class.forName("io.reactivex.android.schedulers.AndroidSchedulers"); } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } return true; } public abstract int getActualCount(); public abstract Fragment getActualItem(int position); public abstract CharSequence getActualPagerTitle(int position);}

js中 options属性 如下:
slideOpts = {
effect: ‘flip’,
loop: true,
slidesPerView: ‘auto’,
autoplay: true,
speed: 300
};
这个可以在首次进来时
会自动轮播,但是当切换页面后,停止了,这个怎么解决!(在ionic3里面是这样处理的:在视图即将出现时,开始调用startAutoplay(),视图即将消失时调用stopAutoplay(),
但是ionic4里面没有了ionViewWillEnter,哪位大佬能告诉我怎么处理

成员位置

  在写carousel-indicators的class的时候,写错了。下面代码块中的红色是正确的写法,在此之前我错把写成;把错写成。

privateButtonbtnPrivilege;

<div id='MySlide' class='carousel slide' data-ride="carousel">      <ol class='carousel-indicators'>          <li data-target="#MySlide" data-slide-to="0" class="active"/>          <li data-target="#MySlide" data-slide-to="1" />          <li data-target="#MySlide" data-slide-to="2" />      </ol>        <!-- Carousel items -->      <div class='carousel-inner'>          <div class='active item'>              <img src="./img/1.png" alt='slide 1' width='480' height='320'/>              <div class="carousel-caption">                  <h3>第一张幻灯片的标题</h3>                  <p>它的说明文字。。。</p>              </div>          </div>          <div class='item'>              <img src="./img/2.png" alt='slide 2' width='480' height='320'/>              <div class="carousel-caption">                  <h3>第二张幻灯片的标题</h3>                  <p>它的说明文字。。。</p>              </div>          </div>          <div class='item'>              <img src="./img/3.png" alt='slide 3' width='480' height='320'/>              <div class="carousel-caption">                  <h3>第三张幻灯片的标题</h3>                  <p>它的说明文字。。。</p>              </div>          </div>      </div>            <!-- Carousel nav -->      <a class='carousel-control left'   data-slide='prev'></a>      <a class='carousel-control right'   data-slide='next'></a>  </div>

private int[][]btnPosition= {new int[4]};

 

Fragment的onCreatView()方法中,(可抽取出去)

显示到第三章图片(正常):

//这里获取屏幕的宽高

图片 4

Display display =
getActivity().getWindowManager().getDefaultDisplay();

再往后,就不正常了,只有两个箭头:

Point point =newPoint();

图片 5

display.getSize(point);


final intscreenWidth = point.x;

final intscreenHeight = point.y;

// 拖动的按钮

btnfloat= view.findViewById(R.id.btn_float);

// 给button添加触摸事件

View.OnTouchListener btnNewerPrivilegeTouchListener
=newView.OnTouchListener() {

intlastX,lastY;// 记录移动的最后的位置

long startTouch;

long endTouch;

public booleanonTouch(View v,MotionEvent event) {

// 获取Action

intea = event.getAction();

switch(ea) {

caseMotionEvent.ACTION_DOWN:// 按下

lastX= (int) event.getRawX();

lastY= (int) event.getRawY();

startTouch= System.currentTimeMillis();

break;

/**

* layout(l,t,r,b) l Left position, relative to parent t Top

* position, relative to parent r Right position, relative to

* parent b Bottom position, relative to parent

* */

case MotionEvent.ACTION_MOVE:// 移动

// 移动中动态设置位置

intdx = (int) event.getRawX() -lastX;

intdy = (int) event.getRawY() -lastY;

intleft = v.getLeft() + dx;

inttop = v.getTop() + dy;

intright = v.getRight() + dx;

intbottom = v.getBottom() + dy;

if(left <0) {

left =0;

right = left + v.getWidth();

}

if(right >screenWidth) {

right =screenWidth;

left = right – v.getWidth();

}

if(top <0) {

top =0;

bottom = top + v.getHeight();

}

if(bottom >screenHeight) {

bottom =screenHeight;

top = bottom – v.getHeight();

}

v.layout(left,top,right,bottom);

// 将当前的位置再次设置

lastX= (int) event.getRawX();

lastY= (int) event.getRawY();

intleft1 = v.getLeft();

inttop1 = v.getTop();

btnPosition[0] =new int[]{left,top,right,bottom};

break;

caseMotionEvent.ACTION_UP:// 脱离

endTouch= System.currentTimeMillis();

if(endTouch-startTouch<=200) {

Intent intent =newIntent(getActivity(),BaseWebViewActivity.class);

intent.putExtra(“url”,NetConfig.HOME_NERNER_PRIVILEGE_URL);

startActivity(intent);

}

break;

}

return false;

}

};

btnfloat.setOnTouchListener(btnNewerPrivilegeTouchListener);

给button设置保存位置

view.addOnLayoutChangeListener((view1,i,i1,i2,i3,i4,i5,i6,i7) -> {

if(btnPosition[0][0] !=0) {

btnPrivilege.layout(btnPosition[0][0],btnPosition[0][1],btnPosition[0][2],btnPosition[0][3]);

}

});

发表评论

电子邮件地址不会被公开。 必填项已用*标注