Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

android - Change the margin of a constraint layout programmatically


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Margins are associated with a View but belong to the ViewGroup which, is in your case, is a ConstraintLayout. Make the margin changes in the ConstraintLayout.LayoutParams

// view is the view to change margins for
val lp = view.layoutParams as ConstraintLayout.LayoutParams
lp.leftMargin = 200 // change to 200px
lp.topMargin = 200
lp.rightMargin = 200
lp.bottomMargin = 200
view.requestLayout() // May or may not be needed depending upon where the code is placed.

If you are changing connections, margins can also be set in a ConstraintLayout using a ConstraintSet.

val cs = ConstraintSet()
cs.clone(layout) // layout is the ConstraintLayout
cs.connect(
    R.id.textView,
    ConstraintSet.START,
    ConstraintSet.PARENT_ID,
    ConstraintSet.START,
    200 // Start margins is now 200px
)
cs.applyTo(layout)

You are setting the visibility of some widgets to View.GONE so maybe you can make use of Gone Margins.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...