问题
I need to be able to change the app:layout_anchorGravity="center"
of the FAB from "center" to "bottom|start" from the code.
I've found this example:
CoordinatorLayout.LayoutParams p = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
p.setAnchorId(xxxx);
fab.setLayoutParams(p);
but it's for setting the anchor and not the anchor gravity.
回答1:
The CoordinatorLayout.LayoutParams
class has the anchorGravity
field for that. For example:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
lp.anchorGravity = Gravity.BOTTOM | GravityCompat.START;
fab.setLayoutParams(lp);
回答2:
Same thing in Kotlin
(rightUglyBox.layoutParams as CoordinatorLayout.LayoutParams)
.anchorGravity
= Gravity.CENTER_VERTICAL or Gravity.LEFT;
*Works on all layout not just FAB
来源:https://stackoverflow.com/questions/38039574/set-fab-anchor-gravity-dynamically