Пользовательский Расширяемый / Разборный CardView - PullRequest
0 голосов
/ 28 декабря 2018

Фон

Я пытался реализовать свой собственный разборный / расширяемый CardView, используя в качестве основы решение, предоставленное ответом на этот ТАК вопрос .Я пытался сделать это в Kotlin вместо Java, что было прекрасно, так как я могу просто добавить функции расширения в класс CardView.Код, который я написал, выглядит следующим образом (примерно переведенный с исходного Java-ответа на Kotlin):

Развернуть / свернуть функции в Kotlin

fun CardView.collapse(collapsedHeight: Int) {
    val initialHeight = measuredHeight
    val distanceToCollapse = initialHeight - collapsedHeight
    val animation = object: Animation() {

        override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
            layoutParams.height = (initialHeight - (distanceToCollapse * interpolatedTime)).toInt()
            requestLayout()
        }

        override fun willChangeBounds() = true
    }

    animation.duration = distanceToCollapse.toLong()
    startAnimation(animation)
}

fun CardView.expand() {
    val initialHeight = height

    measure(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
    val targetHeight = measuredHeight

    val distanceToExpand = targetHeight - initialHeight

    val animation = object : Animation(){

        override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
            layoutParams.height = initialHeight + (distanceToExpand * interpolatedTime).toInt()
            requestLayout()
        }

        override fun willChangeBounds() = true
    }

    animation.duration = distanceToExpand.toLong()
    startAnimation(animation)
}

fun CardView.isExpanded() = layoutParams.height == FrameLayout.LayoutParams.WRAP_CONTENT

Проблема

Функция collapse() работает нормально, но моя настоящая проблема связана с expand().Видео поможет лучше понять, в чем проблема:

enter image description here

Мне кажется, что это как-то связано с тем, что после свертывания CardView, он больше не знает размер всех дочерних представлений, которые он содержит.Это всего лишь моя первоначальная теория ... Мой XML-макет выглядит следующим образом:

XML-макет

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cv_experience"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/base_size"
    app:cardElevation="2dp">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/base_size">

        <TextView
            android:id="@+id/tv_experience_section"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/TextAppearance.AppCompat.Headline"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            tools:text="Experience"/>


        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_experience_companies"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/tv_experience_section"
            app:layout_constraintStart_toStartOf="@id/tv_experience_section" />



    </android.support.constraint.ConstraintLayout>


</android.support.v7.widget.CardView>

У кого-нибудь есть идеи относительно того, что может быть причиной этой проблемы?

Обновление # 1

После дальнейшей отладки я обнаружил, что measuredHeight в expand() возвращает огромное значение: оно всегда где-то около 5000 ... Это объясняет, почему анимация отключенакогда CardView расширен.Тем не менее, я не знаю, почему он возвращает такую ​​огромную стоимость.Код, о котором идет речь, выглядит следующим образом:

fun CardView.expand() {
    val initialHeight = height

    measure(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
    val targetHeight = measuredHeight
    // And so on from previous snippet
}
...