Android : setBackground method changes View's height

Viewed 67

When I change background color programmatically, it stretches the width of TextView.

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textCategory.setText(categoryList.get(position).getName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (categoryIndex == position) {
                holder.textCategory.setBackground(context.getDrawable(R.drawable.categories_background));
            } else {
                holder.textCategory.setBackground(context.getDrawable(R.drawable.temp_background));
            }
        }
    }

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_margin="3dp"
    android:background="@drawable/categories_background"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:textStyle="bold"
        android:fontFamily="sans-serif-light"
        android:textAllCaps="true"
        android:id="@+id/categoryName"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingLeft="10dp"
        android:textColor="#262626"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</androidx.cardview.widget.CardView>

The width of the TextView is getting wide whenever I click. But, I want to keep the width the same and only change background color.

This is the unselected statement for GENERAL tab This is the unselected statement for GENERAL tab

And this is the selected statement And this is the selected statement

2 Answers

Is there any space or different character in there? Could you check it by debugging? Thanks

I also faced this strange issue, for me the height of the control was distorted when changing background color, I used the following workaround when the distortion occurred:

        if (backGroundColorChanged) {
            ViewGroup.LayoutParams layoutParams = newBookmark.getLayoutParams();
            Resources r = getResources();
            float px = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    25, // if I call setBackgroundColor, the height will be distorted -> set it to 25dp
                    r.getDisplayMetrics()
            );
            layoutParams.height = (int)px;
            newBookmark.setBackgroundColor(myContext.getColor(R.color.green) );
            newBookmark.setLayoutParams(layoutParams);
        }
Related