【问题标题】:Programmatically using MATCH_PARENT for a RelativeLayout inside a FrameLayout以编程方式将 MATCH_PARENT 用于 FrameLayout 内的 RelativeLayout
【发布时间】:2014-03-16 00:01:59
【问题描述】:

我正在继承 Horizo​​ntalScrollView(它是一个 FrameLayout)并以编程方式向它添加一个 RelativeLayout。

FrameLayout 正确填充了父视图,但里面的 RelativeLayout 没有显示出来。

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));

CustomHorizo​​ntalScrollView::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));

结果:

RelativeLayout 应该是黑色的并且应该填充父级,但不是。

奇怪的是,如果我以像素为单位指定宽度和高度,而不是使用 MATCH_PARENT,则会出现 RelativeLayout。

this.addView(relativeLayout, new FrameLayout.LayoutParams(90, 90));

这是否意味着我在以编程方式将 RelativeLayout 添加到 FrameLayout 时不能使用 MATCH_PARENT?还是我错过了什么?或者可能 Horizo​​ntalScrollView 只支持有一个固定宽度和高度的孩子?

【问题讨论】:

  • 我发现调用 relativeLayout.layout(l, t, r, b); in onLayout(boolean changed, int l, int t, int r, int b) 使布局匹配父级。但是,子视图未正确对齐(ALIGN_PARENT_LEFT、ALIGN_PARENT_RIGHT)。

标签: android android-layout android-relativelayout android-framelayout fill-parent


【解决方案1】:

我在 Android SDK API 参考中没有找到严格的信息,但实际上 Horizo​​ntalScrollView 是“用户可以滚动的视图层次结构的布局容器,允许它大于物理显示。”
那么,如果其唯一的子项必须具有相同的宽度,为什么还需要 Horizo​​ntalScrollView?
您可能可以尝试以下方法:

this.addView(relativeLayout, new FrameLayout.LayoutParams(90, FrameLayout.LayoutParams.MATCH_PARENT));

...然后RelativeLayout就会出现。
但也许以下内容更有意义:

this.addView(relativeLayout, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT));

然后,RelativeLayout 将足够大以包含其子项,您可以使用 Horizo​​ntalScrollView 滚动它。
Horizo​​ntalScrollView 具有属性 fillViewport,如果需要,您可以将其设置为 true Horizo​​ntalScrollView “拉伸其内容以填充视口”:我认为它只有在内容小于 Horizo​​ntalScrollView 时才有用,但是(我重复一遍),如果内容总是小于 Horizo​​ntalScrollView,那么 Horizo​​ntalScrollView没用。

【讨论】:

  • 感谢您的回复。实际上,我希望RelativeLayout 填充父级,然后向RelativeLayout 添加一个内容视图,该视图将具有比Horizo​​ntalScrollView 更大的视口。但我明白你的意思,我想我必须找到另一种方法来实现我想要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
相关资源
最近更新 更多