【问题标题】:Android: Prepend LinearLayout programmaticallyAndroid:以编程方式添加 LinearLayout
【发布时间】:2013-05-28 23:07:31
【问题描述】:

我在我的应用程序中创建了一个布局,其中包括以下内容:
main_layoutFrameLayout,填满整个屏幕)
-> 包括:main_interfaceLinearLayout,高度/宽度填充父级)

现在我想在main_layout 之前的main_interface 中添加另一个LinearLayout。 我试过这个:

LinearLayout bar = new LinearLayout(this);
        bar.setGravity(Gravity.TOP);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        bar.setLayoutParams(params);
        main_layout.addView(bar);

但这只是与我的main_interface 重叠。

有什么帮助吗?

【问题讨论】:

    标签: java android android-linearlayout prepend


    【解决方案1】:

    如果要将View 添加到ViewGroup 中的特定位置,可以使用addView(view, position)。在这种情况下,假设main_interface是第一个View,则可以调用main_layout.addView(bar, 0)

    但是,您需要先修复布局。如果您使用FrameLayout 作为您的main_layout 并将main_interface 的高度和宽度设置为match_parent,那么它们肯定会重叠。如果您想垂直堆叠Views,请尝试将main_layoutandroid:orientation="vertical" 一起设为LinearLayout

    如果您可以发布您的实际 XML 布局,我可以帮助您修改和测试它。

    【讨论】:

    • 谢谢,你在每一点上都是对的!我将 Layout 更改为 LinearLayout 并将 addView() 的索引设置为零。谢谢!
    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多