I checked a lot of answers, but none helped so far.
I'm trying to extend android's TextView and set the margin of this custom view inside the code, as I'm going to instantiate them on button presses and similar things. It is added to a LinearLayout. That's about what I got:
public class ResultsView extends TextView {
public ResultsView(Context context) {
super(context);
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setMargins(15, 15, 15, 15);
setLayoutParams(layout);
}
}
No sign of margin anywhere.
EDIT: I might want to add, if I assign a margin value in xml, it does work.
You can specify your own custom margin settings. Click Margins, click Custom Margins, and then in the Top, Bottom, Left, and Right boxes, enter new values for the margins.
Margin specifies an extra space outside that View on which we applied Margin. In simple words, Margin means to push outside. Diagrammatically, the margin is shown below: Syntax: android:layout_margin=”size in dp”
We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument.
I think the issue is, that by the time you are trying to add the margin the layoutparams are not set yet, why dont you try overriding this method in your ResultsView class:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
int margin = 15;
margins.topMargin = margin;
margins.bottomMargin = margin;
margins.leftMargin = margin;
margins.rightMargin = margin;
setLayoutParams(margins);
};
And remove the code you have in the Constructor, this way the margin will be applied until we are sure we have a layout object for the view, hope this helps
Regards!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With