[英]Changing ConstraintLayout children's margin and size programmatically
[英]Programmatically set margin to ConstraintLayout
在不同的情況下,我需要更改由 ConstraintLayout 組成的工具欄的邊距。 我嘗試按照以下方式進行
ConstraintLayout.LayoutParams newLayoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
ConstraintLayout.MarginLayoutParams layoutParams = new ConstraintLayout.MarginLayoutParams(newLayoutParams);
layoutParams.setMargins(0, 0, 0, 0);
toolbar.setLayoutParams(newLayoutParams);
但在第二種情況下layoutParams.setMargins(16, 16, 16, 16);
它沒有改變。 所以,有人可以給出其他方式或指出錯誤。 感謝您花時間解決我的問題。
我嘗試使用newLayoutParams.setMargins(54, 54, 54, 0);
這將向左和向右放置邊距,但我仍然需要在它上面放置邊距。
最后在@Aksh 的幫助下,我發現了我的錯誤並解決了我的問題。 如果有人覺得它有用,我會把我的代碼放在下面
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) toolbar.getLayoutParams();
newLayoutParams.topMargin = 0;
newLayoutParams.leftMargin = 0;
newLayoutParams.rightMargin = 0;
toolbar.setLayoutParams(newLayoutParams);
在約束布局中為視圖添加邊距的好方法
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayoutId)
val marginTop = context.getDimension(10f)
constraintSet.setMargin(R.id.tv_user, ConstraintSet.TOP, marginTop)
constraintSet.applyTo(constraintLayoutId)
fun Context.getDimension(value: Float): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, value, this.resources.displayMetrics).toInt()
}
我曾經用 ConstraintSet 修改了一個ConstraintSet
來改變它所鏈接的元素。 我還更改了該過程中的邊距,這是connect
方法的最后一個參數:
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(layout);
constraintSet.connect(
R.id.layout_id,
ConstraintSet.START,
R.id.layout_id2,
ConstraintSet.END,
8);
constraintSet.applyTo(layout);
也許這會給您另一個提示以找到解決方案?
你可能想試試
ViewGroup.MarginLayoutParams params = yourConstraintLayout.getLayoutParams();
params.topMargin = x;
//others shows up in suggestion
我還沒有嘗試過,但我相信它應該可以工作,因為 ConstraintLayout 是一個 ViewGroup。
對於layoutParams.setMargins(w, x, y, z)
,它沒有改變的原因是因為您很可能將這些值視為 Dp 而不是 Px,為此方法接受。
要從 Dp 獲取 Px,您需要使用:
int pxValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.