Android通过编程将边距设置为TableRow中的ImageButton
我在Java代码中定义了一个TableLayout。对于每一行,我将显示三个ImageButton。当按下其中一个按钮时,背景颜色会改变。为了很好地显示它,我设置了10px的填充 我现在遇到的问题是,如果你按下两个相邻的按钮,你就看不到两个按钮之间的断裂。所以我想知道,是否有可能在ImageButtons或其他解决方案上设置一个边距?但是,请尝试Android通过编程将边距设置为TableRow中的ImageButton,android,margin,imagebutton,tablerow,Android,Margin,Imagebutton,Tablerow,我在Java代码中定义了一个TableLayout。对于每一行,我将显示三个ImageButton。当按下其中一个按钮时,背景颜色会改变。为了很好地显示它,我设置了10px的填充 我现在遇到的问题是,如果你按下两个相邻的按钮,你就看不到两个按钮之间的断裂。所以我想知道,是否有可能在ImageButtons或其他解决方案上设置一个边距?但是,请尝试 int leftMargin = 10; ((MarginLayoutParams) imageButton.getLayoutParams()).l
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
。请确保对控件所在的容器使用LayoutParams
。在您的情况下,按钮位于表格行
中,因此请使用表格行。LayoutParams
如果您使用任何其他类型的参数,控件将完全不显示。我尝试过,但我的应用程序崩溃。这就是我使用的代码:我以为您已经在xml中定义了imagebutton,但您是在代码中创建它的,所以您需要为它设置`LayoutParams,而不是获取它们。我将编辑答案。谢谢您的快速回答,但我使用的是表格布局。因此,我已经将LinearLayout替换为TableLayout,但是ImageButtons没有显示在emulator中。此解决方案是否仅绑定到LinearLayout?我的解决方案适用于ListView
,但尝试将LinearLayout.LayoutParams
替换为TableLayout.LayoutParams
,或者可能替换为TableRow.LayoutParams