ListView滑动删除实现之二——scrollTo、scrollBy详解

本文详细解析了Android中ListView的scrollTo和scrollBy方法,通过实例阐述它们的真正意义。scrollTo直接移动视图原点,而scrollBy则在当前位置基础上移动。此外,还探讨了Merge标签在超范围视图显示的应用,展示了如何通过移动视角展示原本不可见的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:一个项目终于要结束了,最最坑的莫过于少估了一个巨复杂的页面的开发时间,队长,你这是要多坑队友才行啊……本来定的一个月要看的内容,看来是高估自己能力了,拖拉严重啊,以后要早起了,把早上的时间也利用起来,一天睡九个小时着时有点多……可趴在床上就想睡这可怎么破……

 

 

相关文章:

1、《 ListView滑动删除实现之一——merge标签与LayoutInflater.inflate()》

2、《ListView滑动删除实现之二——scrollTo、scrollBy详解》

3、《 ListView滑动删除实现之三——创建可滑动删除的ListView》

4、《ListView滑动删除实现之四——Scroller类与listview缓慢滑动》

 

上篇给大家讲了有关merge标签和LayoutInflater的相关内容,这篇就开始接触点实际的东东了,这篇给大家讲讲如何通过scrollTo和scrollBy来移动视图范围。

 

一、scrollTo及scrollBy的真正意义

1、定义

先来看一下scrollTo和scrollBy的用法和含义。

 

 

public void scrollTo(int x, int y) 
public void scrollBy(int x, int y) 

scrollTo:直接将视图原点其移动到目标位置;
scrollBy:在现在视图所在位置的基础上,再向X,Y位置上移动指定像素

2、简单示例

我们先看一个例子,然后再具体讲解,这两个函数的意义。
效果图如下:

在效果图中可以看到:
1、点击scrollTo运行的代码是:scrollTo(100,100),一次将位置移动到指定位置;多次点击无效。
2、点击scrollBy运行的代码是:scrollBy(50,50),在现有位置的基础上一次次移动
3、复位使用代码是:scrollTo(0,0)

大家仔细观察可能会发现一个疑问:为什么scrollTo(100,100),按照正常情况下的坐标正方向来算(向左是X轴正方向,向下是Y轴正方向),不应该往右下方移动吗,为什么这里是往左上方移动呢,正好反过来?
关于这个问题,我们后面再讲,先看看上面效果的代码实现
首先看activity_main.xml布局

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_scroll_to"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="scroll to" />

    <Button
        android:id="@+id/btn_scroll_by"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="scroll by" />

    <Button
        android:id="@+id/btn_scroll_reset"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="复位" />

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical|right"
        android:background="#ff00ff"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:text="@string/hello_world" />
    </LinearLayout>

</LinearLayout>

根据视图效果得出上面的布局代码难度不大,这里要注意的一点是在底部TextView外面包裹了一层LinearLayout,我们调用scrollTo的并不是TextView而是LinearLayout,这也是为什么在布局中,为LinearLayout设置了ID参数:android:id="@+id/root",而textV

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值