Android滚动布局ScrollView滚动到指定的View

本文介绍了如何在Android中使ScrollView滚动到特定View的位置,强调onWindowFocusChanged()是View真正可见的时机,并提供了获取View距离及使用smoothScrollTo()方法的详细说明。

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

本文用于在滚动布局中,操作View到屏幕顶端位置:

Activity生命周期中,onStart, onResume, onCreate都不是真正View真正visible的时间点,真正的visible时间点是onWindowFocusChanged()函数被执行时。
备注:从onWindowFocusChanged被执行起,用户可以与应用进行交互了,而这之前,对用户的操作需要做一点限制。
扩展:如果想要做一个Activity一加载完毕,就触发相应操作的话可以在onWindowFocusChanged()函数内操作

如果View还没有visible,使用View的getWidth() 、getHeight() 方法来获取该View的宽和高,返回的值为0。onWindowFocusChanged()内调用getWidth() 、getHeight() 方法可以正常获取宽和高。
获取距离

获取View距离父容器的距离:

 @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        y = view.getTop();  //顶部距离父容器的Y轴距离

    }
方法源码

smoothScrollTo(x,y):

/** 
     * Like {@link #scrollTo}, but scroll smoothly instead of immediately. 
     * 
     * @param x the position where to scroll on the X axis 
     * @param y the position where to scroll on the Y axis 
     */  
    public final void smoothScrollTo(int x, int y) {  
        smoothScrollBy(x - mScrollX, y - mScrollY);  
    }  
使用方法

利用scrollView的smoothScrollTo()方法操作View:


scrollView.smoothScrollTo(0,y);
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值