Search code examples
androidscrollhorizontalscrollview

Android scrolling on a HorizontalScrollView


I have a HorizontalScrollView with a LinearLayout inside. This LinearLayout is populated (dynamically) with a lot of TextViews. I want to scroll my HorizontalScrollView to a specified TextView depending on some index. I try this but doesn't work

while (!this.stopsCursor.isAfterLast()) {
        int index = this.stopsCursor.getInt(this.stopsCursor.getColumnIndex("index"));
        if (index == session.getServiceStopIndex()) {
            TextView view = (TextView) this.linearLayout.getChildAt(index);
            StyleHelper.setStopHighlight(view);
            Log.v("TEST", "Left : " + view.getLeft() + "  Right : " + view.getRight());
            int offsetX = ((view.getLeft() + view.getRight()) / 2);
            this.horizontalScrollView.scrollTo(offsetX, 0);

        }
        this.stopsCursor.moveToNext();
    }

My logger show me Left : 0 Right : 0 Can someone help me? Thanks in advance!


Solution

  • The problem is probably that you are attempting to get the left and right of the view before layout. You need to move this code later in the layout flow. It's hard to say exactly where to move it without more context as to when you want to scroll, but if it's immediately after creation (and I assume that you're populating the LinearLayout somewhere around the Activity's onCreate) then you might want to look at overriding View.onSizeChanged and doing it around then.