Search code examples
androidhorizontalscrollview

HorizontalScrollView.getMeasuredWidth() returns 0


I am adding horizontalScrollView programatically , but when I try to do horizontalScrollView.getMeasuredWidth() it keeps returning 0.

void addCategory(String catTitle) {
    mVideos = mShows.get(catTitle);
    LinearLayout theLayout = (LinearLayout)findViewById(R.id.activitymain);
    TextView textview=(TextView)getLayoutInflater().inflate(R.layout.categorytitle,null);
    textview.setTextColor(Color.CYAN);
    textview.setTextSize(20);
    textview.setText(catTitle);

   HorizontalScrollView horizontalScroll = new HorizontalScrollView (this,null);
    LinearLayout LL = new LinearLayout(this);
    LL.setOrientation(LinearLayout.HORIZONTAL);
    LayoutParams LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    LL.setLayoutParams(LLParams);
    HorizontalGalleryAdapter adapter = new HorizontalGalleryAdapter(this,mVideos);
    for (int i = 0; i < adapter.getCount(); i++) {
          View item = adapter.getView(i, null, null);
          LL.addView(item);
    }



    horizontalScroll.addView(LL);
    int maxScrollX = horizontalScroll.getChildAt(0).getMeasuredWidth()-horizontalScroll.getMeasuredWidth();
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Reset...");
    String max= String.valueOf(maxScrollX);

Solution

  • Ok, I see the problem. You create a HorizontalScrollView, add a child to it, and then immediately try to get its measured width.

    You cannot do this. You must add the horizontal scroll view to an existing already-drawn view in your activity first, because otherwise it doesn't have set dimensions yet.

    Think about how would it know how many pixels WRAP_CONTENT will set the dimension to before its laid out in your view? If you add it to an existing, already-laid-out view in your activity, then that WRAP_CONTENT will actually get converted to some height.

    It looks like you kind-of have a loop - horizontalScroll's dimensions depend on its content (WRAP_CONTENT), yet the content's (LinearLayout's) dimensions depend on the horizontalScroll's dimensions. This does not make sense. Perhaps try MATCH_PARENT for at least the width dimensions of your horizontal scroll view. Then, make sure to not look at dimensions until the view has been drawn.