Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 720
tom Avatar asked Jul 19 '13 20:07

tom


People also ask

How do I set custom view margins?

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.

What is layout_ margin in Android?

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”

How do you set margins in Java?

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.


1 Answers

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!

like image 100
Martin Cazares Avatar answered Sep 28 '22 18:09

Martin Cazares