I have a guideline in constraint layout like this
There is two ways to do it:
This method get a specific parameter from the
ConstraintLayout
and modify it.
Guideline guideLine = (Guideline) findViewById(R.id.your_guideline);
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideLine.getLayoutParams();
params.guidePercent = 0.45f; // 45% // range: 0 <-> 1
guideLine.setLayoutParams(params);
This method consists in cloning the
ConstraintLayout
attributes, modifying them and then applying to theView
.BUT it's very slow.
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.your_constraint_with_guideline);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.setGuidelinePercent(R.id.your_guideline, 0.07f); // 7% // range: 0 <-> 1
TransitionManager.beginDelayedTransition(constraintLayout);
constraintSet.applyTo(constraintLayout);
To test those methods I created a parallax animation using a GuideLine
and a ScrollView
on top.
On the AndroidManifest.xml
, inside your Activity
, add this: android:hardwareAccelerated="true"
.
...
MainActivity.java
Guideline guideTopInfo;
ConstraintLayout constraintLayout;
ConstraintLayout.LayoutParams params;
ConstraintSet constraintSet;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guideTopInfo = (Guideline) findViewById(R.id.guideline2);
constraintLayout = (ConstraintLayout) findViewById(R.id.constraint_root);
params = (ConstraintLayout.LayoutParams) guideTopInfo.getLayoutParams();
//constraintSet = new ConstraintSet();
//constraintSet.clone(constraintLayout);
final ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_front);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
float percentage = scrollView.getScrollY() * 0.0001f; // 0.001f faster // 0.00001f slower parallax animation
Log.d("mLog", String.valueOf(percentage));
if(percentage >= 0) {
// my XML percentage value was 12%
params.guidePercent = 0.12f - percentage; // up
//params.guidePercent = 0.12f + percentage; // downm
guideTopInfo.setLayoutParams(params);
//constraintSet.setGuidelinePercent(R.id.guideline2, 0.12f - percentage);
//TransitionManager.beginDelayedTransition(constraintLayout);
//constraintSet.applyTo(constraintLayout);
}
}
});
}
My other answer about parallax if anyone is interested. ;)