WojciechKo
WojciechKo

Reputation: 1531

How to set Margins in class inherited from RelativeLayout

How can I set margins in class extends from RelativeLayout?
I have tried this but it doesn't work:

public class MyRelativeLayout extends RelativeLayout {
    int margin = 50;

    public MyRelativeLayout(Context context) {
        super(context);
        setLook();
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLook();
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setLook();
    }

    private void setLook() {
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(margin, margin, margin, margin);
        setLayoutParams(params);
    }
}

How should I do this?

Update:

Usage of this view:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <info.korzeniowski.widget.MyRelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center" >

    //content
    </info.korzeniowski.widget.MyRelativeLayout>
</ScrollView>

Upvotes: 3

Views: 769

Answers (1)

Xaver Kapeller
Xaver Kapeller

Reputation: 49837

A custom View should NEVER define its own margins. Margins are purely used for layouting and you cannot reliably use them to design your custom View.

You can essentially replicate the effect margins have without any of the problems that come with margins by using paddings and a child View:

public class MyRelativeLayout extends RelativeLayout {

    private final int padding;

    public MyRelativeLayout(Context context) {
        super(context);

        // Use 50 dip instead of 50 pixels
        this.padding = LayoutHelper.dpToPixel(context, 50);

        setLook();
    }

    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        // Use 50 dip instead of 50 pixels
        this.padding = LayoutHelper.dpToPixel(context, 50);

        setLook();
    }

    public MyRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // Use 50 dip instead of 50 pixels
        this.padding = LayoutHelper.dpToPixel(context, 50);

        setLook();
    }

    private void setLook() {
        setPadding(this.padding, this.padding, this.padding, this.padding);

        final View innerView = ...;
        final LayoutParams innerViewParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addView(innerView, innerViewParams);
    }
}

The View called innerView should contain all the content you want to display in your custom View.

Upvotes: 1

Related Questions