以编程方式添加的视图不正常

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应该分别替换为params2params3params4

更新: 此外,您应该为所有不在顶部的视图指定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 这并不意味着你不应该这样做。还要检查我的更新答案 是的,已修复。谢谢。

以上是关于以编程方式添加的视图不正常的主要内容,如果未能解决你的问题,请参考以下文章

UIImageView(以编程方式创建)未显示

以编程方式修改自动布局约束时视图不更新

以编程方式将按钮添加到集合视图单元格

在 iPad 上以编程方式添加子视图,硬编码

以编程方式创建 UIToolbar

以编程方式使用自动布局将子视图添加到 UICollectionView 不起作用