简体   繁体   中英

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:

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

BUT viewLeft and viewWidth are 0 as the view is not measured yet. 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. 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.

In this post: getWidth() and getHeight() of View returns 0 you have a lot of good options to solve this problem. Particularly I use this one:

Listen to Draw/Layout Events: ViewTreeObserver

A ViewTreeObserver gets fired for different drawing events. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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