android - 如何在继承自 RelativeLayout 的类中设置 Margins

标签 android layout margin

如何在 RelativeLayout 扩展类中设置边距?
我试过这个但它不起作用:

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);
    }
}

我应该怎么做?

更新:

这个 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>

最佳答案

自定义View 不应永远 定义自己的边距。边距纯粹用于布局,您不能可靠地使用它们来设计您的自定义 View

通过使用填充和子 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);
    }
}

名为 innerViewView 应该包含您要在自定义 View 中显示的所有内容。

关于android - 如何在继承自 RelativeLayout 的类中设置 Margins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24677918/

相关文章:

android - Android中如何写特殊字符

Android >=5.0 MediaPlayer 准备失败

layout - 是否定义了 D 结构的确切布局?

wpf - 居中 WPF 控件

android - 无法弄清楚如何使用 ImageViewTouch Hook

android - 在模拟器 (Android) 上安装 Google Plus 应用程序

html - 使用 Bootstrap 网格从缩略图中删除边距

html - 实现列之间的框架边距

适用于手机的 Android 条件布局 :tablets

html - CSS根据另一个div的动态高度定位一个div