用户登录
用户注册

分享至

Android使用ScrollView实现滚动效果

  • 作者: 叶量辰
  • 来源: 51数据库
  • 2021-07-11

本文实例为大家分享了scrollview实现滚动效果的具体代码,供大家参考,具体内容如下

如果长文本的内容超过一屏幕 则只能显示一屏幕的内容
设置scrollview 通过滚动浏览下面的内容

若将标签更改为<horizontalscrollview></horizontalscrollview>则为水平滚动效果

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.constraintlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.example.lenovo.scrollview.mainactivity">
 
  <scrollview
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none"><!--不显示右侧滚动条 -->
 
    <textview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/content"
      />
 
  </scrollview>
 
</android.support.constraint.constraintlayout>

mainactivity文件:

package com.example.lenovo.scrollview;
 
import android.annotation.suppresslint;
import android.app.activity;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.util.log;
import android.view.motionevent;
import android.view.view;
import android.widget.button;
import android.widget.scrollview;
import android.widget.textview;
 
public class mainactivity extends activity {
 
  private textview tv;
  private scrollview scrollview;
 
  @suppresslint("clickableviewaccessibility")
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    tv=findviewbyid(r.id.content);
    tv.settext(getresources().getstring(r.string.content));
 
    scrollview=findviewbyid(r.id.scroll);
    //设置监听器
    scrollview.setontouchlistener(new view.ontouchlistener() {
      public boolean ontouch(view view, motionevent motionevent) {
        //对motionevent的参数作判断
        switch (motionevent.getaction()){
          case motionevent.action_up:
          {
            break;
          }
          case motionevent.action_down:
          {
            break;
          }
          case motionevent.action_move:{
            /*
            * (1)getscrolly()--滚动条滑动的距离,从0开始计算
            * (2)getmeasuredheight()--全长
            * (3)getheight()--一屏幕的高度
            * */
            //顶部状态
            if(scrollview.getscrolly()<=0){
              log.i("main","滑动到顶部");
            }
            //底部状态
            if(scrollview.getchildat(0).getmeasuredheight()<=scrollview.getheight()+scrollview.getscrolly()){
              log.i("main","滑动到底部");
              tv.append(getresources().getstring(r.string.content));//滑动到底部时再次追加本篇文字
            }
 
            break;
          }
 
        }
        return false;
      }
    });
  }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

软件
前端设计
程序设计
Java相关