简体   繁体   English

Android-将项目添加到滚动视图并以编程方式滚动

[英]Android - Adding an item to a scroll view and scroll programmatically

I have an empty scrollview. 我有一个空的滚动视图。 I create with inflater a text view, add it to the ScrollView programmatically and then do: 我用充气机创建一个文本视图,以编程方式将其添加到ScrollView中,然后执行以下操作:

rsView.smoothScrollBy((viewLeft + viewWidth / 2) - center, 0);

BUT viewLeft and viewWidth are 0 as the view is not measured yet. 但是viewLeft和viewWidth为0,因为尚未测量视图。 Any suggestions on how to make it scroll the view properly? 关于如何使其正确滚动视图的任何建议?

Move the smoothScrollBy() call to a Runnable and post that to the new TextView 's handler after it's been added, which will cause it to run after it's been laid out. 在添加了它之后,将smoothScrollBy()调用移至Runnable并将其发布到新的TextView的处理程序中,这将使其在布局后运行。 For example: 例如:

viewGroup.addView(childView);
childView.post(new Runnable() {
        @Override
        public void run() {
            rsView.smoothScrollBy((childView.getLeft() + childView.getWidth() / 2) - center, 0);
        }
    }
);

I'm not sure how you're calculating center , but if it depends on the new TextView 's dimensions, you'll need to move the calculation to the Runnable , as well. 我不确定您如何计算center ,但是如果它取决于新TextView的尺寸,则还需要将计算移到Runnable

In this post: getWidth() and getHeight() of View returns 0 you have a lot of good options to solve this problem. 在这篇文章中: View的getWidth()和getHeight()返回0,您有很多不错的选择来解决此问题。 Particularly I use this one: 特别是我用这个:

Listen to Draw/Layout Events: ViewTreeObserver 收听绘图/布局事件:ViewTreeObserver

A ViewTreeObserver gets fired for different drawing events. 一个ViewTreeObserver被激发用于不同的绘图事件。 Usually the OnGlobalLayoutListener is what you want for getting the measurement, so the code in the listener will be called after the layout phase, so the measurments are ready: 通常,OnGlobalLayoutListener是获取度量所需的,因此将在布局阶段之后调用侦听器中的代码,因此可以进行测量:

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            rsView.smoothScrollBy((viewLeft + viewWidth / 2) - center, 0);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM