inline fun MarginLayoutParams.updateMargins(
@Px left: Int = leftMargin,
@Px top: Int = topMargin,
@Px right: Int = rightMargin,
@Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin
params.updateMargins(left = 8)
inline fun MarginLayoutParams.updateMarginsRelative(
@Px start: Int = marginStart,
@Px top: Int = topMargin,
@Px end: Int = marginEnd,
@Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin
params.updateMargins(start = 8)
以下扩展属性便于获取当前页边距:
inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);
我现在无法测试它,所以我的演员阵容可能会有点偏离,但是需要修改LayoutParams来更改边距
注
Don't forget that if your TextView is inside, for example, a
RelativeLayout, one should use RelativeLayout.LayoutParams instead of
LinearLayout.LayoutParams
# 4 楼答案
使用此功能设置所有类型的页边距
public void setViewMargins(Context con, ViewGroup.LayoutParams params,
int left, int top , int right, int bottom, View view) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel_left = (int) (left * scale + 0.5f);
int pixel_top = (int) (top * scale + 0.5f);
int pixel_right = (int) (right * scale + 0.5f);
int pixel_bottom = (int) (bottom * scale + 0.5f);
ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);
view.setLayoutParams(params);
}
# 1 楼答案
更新:Android KTX
Core KTX module为作为Android框架一部分的公共库提供扩展,其中^{}
以下扩展功能便于处理边距:
设置
ViewGroup
的MarginLayoutParams
中所有轴的边距。(必须以像素为单位提供尺寸,如果要使用dp,请参阅最后一节)更新
ViewGroup
的ViewGroup.MarginLayoutParams
中的页边距更新
ViewGroup
的MarginLayoutParams
中的相对边距(开始/结束,而不是左/右)以下扩展属性便于获取当前页边距:
dp
代替px
:如果要使用
dp
(与密度无关的像素)而不是px
,则需要首先转换它们。使用以下扩展属性可以轻松完成此操作:然后可以调用前面的扩展函数,如:
旧答案:
在Kotlin中,您可以声明如下扩展函数:
然后你可以这样称呼它:
或:
# 2 楼答案
使用LayoutParams(如前所述)。但是,请小心选择哪个布局参数。根据https://stackoverflow.com/a/11971553/3184778“您需要使用与正在处理的视图的父视图相关的视图,而不是实际视图”
例如,如果TextView位于TableRow内,则需要使用TableRow。LayoutParams而不是RelativeLayout或LinearLayout
# 3 楼答案
编辑:一种更通用的方法,不依赖于布局类型(除此之外,它是一种支持边距的布局类型):
您应该检查文档中的TextView。基本上,您需要获取TextView的LayoutParams对象,修改边距,然后将其设置回TextView。假设它处于线性布局,请尝试以下操作:
我现在无法测试它,所以我的演员阵容可能会有点偏离,但是需要修改LayoutParams来更改边距
注
# 4 楼答案
使用此功能设置所有类型的页边距