NullPointerException
NullPointerException

Reputation: 37579

Anomalous WRAP_CONTENT behaviour

It's supposed that WRAP_CONTENT does this:

Special value for the height or width requested by a View. WRAP_CONTENT means that the view wants to be just large enough to fit its own internal content, taking its own padding into account.

But the reality is different

If you create a very long textview with a lot of height, bigger than the screen height, then, WRAP_CONTENT applied to the height of that textview has an erroneal behaviour, because limits the textview height to the screen height.

android:layout_height="wrap_content"

Why WRAP_CONTENT has that erroneal behaviour?

How can you set to a view to have the size of it's content without being limited by the screen height?

Complete XML file (this is a screen for end titles of a game, the text will be animated up, because of that is hidden below the screen):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/creditsTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/credits_big"
        android:textAlignment="center"
        android:textColor="@color/font"
        android:textSize="@dimen/medium_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>

Upvotes: 2

Views: 83

Answers (1)

Cheticamp
Cheticamp

Reputation: 62821

Try the following to get the true height of the text in the TextView and to resize the view to match.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mainLayout.doOnLayout {
            val tv = findViewById<TextView>(R.id.creditsTextView)
            val layout = tv.layout
            val lp = tv.layoutParams
            lp.height = layout.height
            tv.layoutParams = lp
        }
    }
}

Although this works, it makes me feel a little uneasy. You may want to look at other ways to accomplish your credits scroll.

Upvotes: 0

Related Questions