How to prevent child View from inheriting its parent setAlpha value in Android

133 viewsCode SolutionssetAlpha textviewopacity
0

In this code solution section, I document some challenges I have faced while coding and how I was able to solve them.

The child TextView in the code below inherits alpha value from parents layout.

<androidx.appcompat.widget.LinearLayoutCompat
            android:id="@+id/upper_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingStart="12dp"
            android:paddingEnd="12dp"
            android:setAlpha="0.5"
            android:orientation="vertical">
            <TextView
                android:id="@+id/double_tapped"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/colorDark"
                android:text="Double Tap To Write Text"
                android:textColor="@color/colorWhite"
                android:fontFamily="@font/robotolight"
                android:textSize="14sp"
                android:textStyle="bold"       
                android:layout_gravity="center"/>
         </androidx.appcompat.widget.LinearLayoutCompat>

Solution

There are some few hack online on how to solve this issue. But how I was able to solve it is to use the Android ColorUtils class with its method setAlphaComponent(Color.WHITE, 30);

The code snippets is show below.

int alphaColor = ColorUtils.setAlphaComponent(Color.WHITE, 30);
 TextView textView = (TextView)findViewById(R.id.textview);
textView.setTextColor(alphaColor);

If you have alternative solution to the above solution kindly share it with us.

Asked question