ConstraintSet>>applyTo Setting the Alpha Of a TextView to 1f

Viewed 756

I'm working on an Android app (Target API 28, min API 22) written in Kotlin using Android Studio.

I have a ConstraintLayout with a number of Views added to it. Among them is a simple TextView. I want the TextView to initialize with an alpha of 0f (invisible) and then later on (via animation) change its value to 1f to make them visible. I got the animation working, but the initial alpha did not appear to be having any effect. I eventually traced the issue to the ConstraintSet>>applyTo(...) method. The snippet below shows that ConstraintSet>>applyTo(...) sets the alpha of the TextView back to 1f even though I explicitly set it to 0f.

val textView = TextView(context)
textView.id = View.generateViewId()
textView.text = "Hello World"
addView(textView)

val set ConstraintSet()
set.constrainHeight(textView.id, WRAP_CONTENT)
set.constrainWidth(textView.id, WRAP_CONTENT)
set.connect(textView.id, TOP, PARENT_ID, TOP)
set.connect(textView.id, START, PARENT_ID, START)
set.connect(textView.id, END, PARENT_ID, END)
set.connect(textView.id, BOTTOM, PARENT_ID, BOTTOM)
println("1. textView=${textView.alpha}")
textView.alpha = 0f
println("2. textView=${textView.alpha}")
set.applyTo(this)
println("3. textView=${textView.alpha}")
textView.alpha = 0f
println("4. textView=${textView.alpha}")

When I run my app, the below output is generated in the Run window:

I/System.out: 1. textView=1.0
              2. textView=0.0
              3. textView=1.0
              4. textView=0.0

By setting the alpha of the TextView after the ConstraintSet>>applyTo(...) call, I achieve an alpha of 0f.

My question is...why? Why is ConstraintSet changing properties of the views it's constraining that have (seemingly) nothing to do with constraints? Are there other properties that ConstraintSet sets when it is applied?

1 Answers

Yeah it's pretty counter intuitive. ConstraintSet creates an extension of actual LayoutParams before applying them.

This extension is android.support.constraint.Constraints.LayoutParams, at this moment (decompiled from constraint-layout:1.1.3) it stores the following (with default values):

public static class LayoutParams extends android.support.constraint.ConstraintLayout.LayoutParams {
    public float alpha = 1.0F;
    public boolean applyElevation = false;
    public float elevation = 0.0F;
    public float rotation = 0.0F;
    public float rotationX = 0.0F;
    public float rotationY = 0.0F;
    public float scaleX = 1.0F;
    public float scaleY = 1.0F;
    public float transformPivotX = 0.0F;
    public float transformPivotY = 0.0F;
    public float translationX = 0.0F;
    public float translationY = 0.0F;
    public float translationZ = 0.0F;

    //... rest of class
}
Related