Search code examples
androidkotlintextview

Android: How to set a textview's text size based on another text view programmatically


So I have two text views, one a that has a specific height and auto-size properties implemented in it. The other is a normal multiple lined text view with wrap content as height.

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/tvMovieRating"
            android:layout_width="match_parent"
            android:layout_height="@dimen/tvOthersActivityMovieHeight"
            android:layout_marginStart="@dimen/text_view_movie_description_margin_start"
            android:layout_marginHorizontal="@dimen/mainCLMarginActivityMovie"
            android:text="@string/movieRatingHint"
            android:textColor="@color/white"
            app:autoSizeMaxTextSize="@dimen/all_auto_max_text_sizes"
            app:autoSizeMinTextSize="@dimen/all_auto_min_text_sizes"
            app:autoSizeStepGranularity="@dimen/all_auto_size_step_granularities"
            app:autoSizeTextType="uniform"
            app:layout_constraintTop_toBottomOf="@id/tvMovieNameAndDate"
            />

        <TextView
            android:id="@+id/tvMovieDescriptionList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/text_view_movie_description_margin_start"
            android:layout_marginHorizontal="@dimen/mainCLMarginActivityMovie"
            android:textSize="268sp"
            android:text="@string/lorem_ispum"
            android:textColor="@color/white"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tvNonChangeableDescriptionText"
            />

Now what I'm trying to set the 2nd textView's textSize size based on the first textView's textSize. I've tried:

binding.tvMovieDescriptionList.textSize = binding.tvMovieRating.textSize

but it didn't work, any help?


Solution

  • You cannot directly do the following: setTextSize(getTextSize()).

    The reason is the getTextSize() is returning the exact pixel size, meanwhile setTextSize() sets the scaled pixel unit. The unit does not align with these functions.

    So for the simplest way, you can mention the unit when you are setting the size:

    binding.tvMovieDescriptionList.setTextSize(TypedValue.COMPLEX_UNIT_PX, binding.tvMovieRating.textSize)
    

    Or you can calculate the scaled pixel unit yourself before setting:

    val metrics = resources.displayMetrics
    binding.tvMovieDescriptionList.textSize = binding.tvMovieRating.textSize / metrics.density