安卓ScrollView实现自动滚屏

来源:互联网 发布:手机图片标注软件 编辑:程序博客网 时间:2024/05/08 09:05

  今天因项目需要,制作一个ScrollView的自动滚屏。在网上找了很多的代码,还是无法具体实现。具体网页有这些:比如http://www.eoeandroid.com/forum.php?mod=viewthread&tid=46764,都是大同小异。主要的实现代码就是这些。可是仍然会有人不知道具体怎么使用。比如,布局xml你可能写的不符合规则。还有可能不知道放在哪里才可以实现滚屏。

  首先,先把他的代码贴出来:

首先1

获得ScrollView sc = (ScrollView) findViewById(R.id.scroll);//scroll对象
     LinearLayout mlayout = (LinearLayout) findViewById(R.id.mlayout);//scrollView中包含的布局对象
2,定义一个Handler
private final Handler mHandler = new Handler();

<span style="font-family:Arial;">private Runnable ScrollRunnable= new Runnable() {                @Override                public void run() {                                     int off = mlayout.getMeasuredHeight() - sc.getHeight();//判断高度 </span>
<span style="white-space: pre;"></span><span style="font-family:Arial;">if (off > 0) {</span>
<span style="font-family:Arial;">                                sc.scrollBy(0, 30);                                if (sc.getScrollY() == off) {                                        Thread.currentThread().interrupt();                                } else {                                        mHandler.postDelayed(this, 1000);                                }                        }                }        };</span>
这就是核心代码,当然还有一部分代码,一般搜出来的网页上是没有的。那就是怎么具体用他,还需要设置一个监听器,就是addOnLayoutChangeListener。在这个监听器里面调用 mHandler.post(ScrollRunnable),就可以了。

样板布局如下:

<span style="font-family:Arial;"><ScrollView        xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/nameScroll" >                <LinearLayout            android:layout_width="match_parent"    android:layout_height="100dp"    android:orientation="vertical"        android:focusable="false"              android:focusableInTouchMode="false"    android:id="@+id/layout" >                    </LinearLayout></ScrollView></span> 
具体实现就不用赘述了。留下一个Demo供大家参考~

下载地址:http://pan.baidu.com/s/1dD6FPeD 





0 0
原创粉丝点击