【问题标题】:Android programatically set margin to ImageButton in TableRowAndroid以编程方式将边距设置为TableRow中的ImageButton
【发布时间】:2011-06-19 05:03:15
【问题描述】:

我在我的 Java 代码中定义了一个 TableLayout。对于每一行,我显示三个 ImageButton。当按下其中一个按钮时,背景颜色会发生变化。为了更好地显示它,我设置了 10px 的填充。

我现在遇到的问题是,如果您按下两个相邻的按钮,则不会完全看到按钮之间的中断。所以我想知道,是否有可能在 ImageButtons 或其他解决方案上设置边距?

【问题讨论】:

    标签: android margin imagebutton tablerow


    【解决方案1】:

    试试

    int leftMargin = 10;
    ((MarginLayoutParams) imageButton.getLayoutParams()).leftMargin = leftMargin;
    

    编辑: 如果你不使用xml中定义的ImageButton,你必须像这样设置LayoutParams

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                            LayoutParams.WRAP_CONTENT);
    params.leftMargin = 10;
    b.setLayoutParams(params);
    

    这里我假设您在列表项中使用LinearLayout

    【讨论】:

    • 我试过了,但我的应用程序崩溃了。这是我使用的代码:pastebin.com/ibB3840J
    • 我以为你在 xml 中定义了 imagebutton,但是你在代码中创建了它,所以你需要将 `LayoutParams 设置为它而不是获取它们。我会编辑答案。
    • 感谢您的快速回答,但我使用的是 TableLayout。所以我已经将 LinearLayout 替换为 TableLayout,但 ImageButtons 没有显示在模拟器中。此解决方案是否仅绑定到 LinearLayout?
    • 我的解决方案是ListView,但尝试用TableLayout.LayoutParams替换LinearLayout.LayoutParams
    • 或者TableRow.LayoutParams
    【解决方案2】:

    确保对控件所在的容器使用LayoutParams。在您的情况下,按钮位于TableRow,因此如果您使用任何其他类型的参数,请使用TableRow.LayoutParams,控件将不会完全显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多