【发布时间】:2014-08-31 21:49:50
【问题描述】:
如何在从 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);
}
}
我应该怎么做?
更新:
这个视图的用法:
<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>
【问题讨论】:
-
不起作用是什么意思?
-
您是否将边距与填充混淆了?请解释到底是什么不起作用。
-
@blackbelt 这意味着它不起作用。
-
@XaverKapeller 我不是,当我使用 setPadding() 它工作正常。我需要使用边距,但我不知道如何使用。
-
@WojciechKo 为什么需要使用边距?自定义
View设置它自己的边距似乎很奇怪。通常这取决于View的布局。那么为什么不能使用填充呢?你首先想做什么?边距并不总是有效,它们被一些Views忽略。