Android programatically set margin to ImageButton in TableRow

Hannelore picture Hannelore · Mar 31, 2011 · Viewed 9.6k times · Source

I have defined a TableLayout in my Java code. For each row, I'm displaying three ImageButtons. When one of those buttons is pressed, the background color changes. To display it nicely, I have set a padding of 10px.

The problem I'm having now is that if you press two buttons that are next to each other, you don't exactly see a break between the buttons. So I'm wondering, is there a possibility to set a margin on the ImageButtons or an other solution whatshowever?

Answer

ernazm picture ernazm · Mar 31, 2011

Try

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

EDIT: If you don't use ImageButton defined in xml, you have to set LayoutParams like this:

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

Here I assume you use LinearLayout in your list item.