I'm subclassing HorizontalScrollView (which is a FrameLayout) and adding a RelativeLayout to it programmatically.
The FrameLayout correctly fills the parent view, but RelativeLayout inside doesn't show up.
MainActivity::OnCreate()
setContentView(R.layout.activity_main);
CustomHorizontalScrollView custom = new CustomHorizontalScrollView(this);
ViewGroup contentView = (ViewGroup) findViewById(R.id.content);
contentView.addView(custom,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 180));
CustomHorizontalScrollView::Constructor()
this.setBackgroundColor(Color.MAGENTA);
relativeLayout = new RelativeLayout(context);
relativeLayout.setBackgroundColor(Color.BLACK);
this.addView(relativeLayout, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
Result:
The RelativeLayout should be black and should fill parent but is not.
The weird thing is that if I specify width and height in pixels instead using MATCH_PARENT, the RelativeLayout appears.
this.addView(relativeLayout, new FrameLayout.LayoutParams(90, 90));
Does that mean that I can't use MATCH_PARENT when programmatically adding a RelativeLayout to a FrameLayout? Or am I missing something? Or maybe HorizontalScrollView only supports having a child with fixed width and height?
I do not find strict info in Android SDK API Reference, but actually the HorizontalScrollView is a "Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display."
So, why do you need a HorizontalScrollView if its unique child must have the same width?
Likely, you can try the following:
this.addView(relativeLayout, new FrameLayout.LayoutParams(90, FrameLayout.LayoutParams.MATCH_PARENT));
... and the RelativeLayout will appear.
But maybe the following makes more sense:
this.addView(relativeLayout, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT));
Then the RelativeLayout will be large enough to contain its children and you'll can scroll it using the HorizontalScrollView.
The HorizontalScrollView has the property fillViewport that you can set to true if you want
that the HorizontalScrollView "stretch its content to fill the viewport": I think it can be useful only when the content is less large than the HorizontalScrollView, but (I repeat), if the content is ALWAYS less large than the HorizontalScrollView, then the HorizontalScrollView is useless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With