以编程方式添加的视图不正常
Posted
技术标签:
【中文标题】以编程方式添加的视图不正常【英文标题】:Programmatically added Views not behaving 【发布时间】:2014-09-10 20:19:55 【问题描述】:我已经创建了许多自定义视图,我正在尝试将它们添加到我的片段中。他们被添加了,但我似乎无法让他们去我想去的地方。应该有 2 列和 3 行,但它最终为 1 列,所有自定义视图都堆叠在一起。这是我添加视图并将布局参数设置为片段布局的代码:
RelativeLayout fm = (RelativeLayout) view.findViewById(R.id.fragmentLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
CustomImages cs = new CustomImages(getActivity());
cs.setId(R.id.one);
cs.setLayoutParams(params);
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.RIGHT_OF, cs.getId());
CustomImages2 cs2 = new CustomImages2(getActivity());
cs2.setId(R.id.two);
cs2.setLayoutParams(params);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params2.addRule(RelativeLayout.BELOW, cs2.getId());
CustomImages3 cs3 = new CustomImages3(getActivity());
cs3.setId(R.id.three);
cs3.setLayoutParams(params);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params3.addRule(RelativeLayout.RIGHT_OF, cs3.getId());
CustomImages4 cs4 = new CustomImages4(getActivity());
cs4.setId(R.id.four);
cs4.setLayoutParams(params);
RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params4.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params4.addRule(RelativeLayout.BELOW, cs4.getId());
CustomImages5 cs5 = new CustomImages5(getActivity());
cs5.setId(R.id.five);
cs5.setLayoutParams(params);
【问题讨论】:
【参考方案1】:cs3.setLayoutParams(params);
cs4.setLayoutParams(params);
cs5.setLayoutParams(params);
我认为params
应该分别替换为params2
、params3
和params4
。
更新:
此外,您应该为所有不在顶部的视图指定LAYOUT_BELOW
,并正确执行:
params2.addRule(RelativeLayout.BELOW, cs.getId()); // not cs2
params3.addRule(RelativeLayout.BELOW, cs2.getId()); // add this
params4.addRule(RelativeLayout.BELOW, cs3.getId()); // not cs4
【讨论】:
我已经尝试过了,它的行为完全相同。 @MaxKleine 这并不意味着你不应该这样做。还要检查我的更新答案 是的,已修复。谢谢。以上是关于以编程方式添加的视图不正常的主要内容,如果未能解决你的问题,请参考以下文章