Search code examples
androidtextviewmargin

Margin on custom TextView


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.


Solution

  • 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!