带有子元素的 Android 自定义可展开/可折叠视图

问题描述

我正在 android 中开发一个自定义的可扩展视图。 目标是我可以在 xml 文件中添加子元素,当用户单击展开/折叠按钮时,它们将展开和折叠,如下图所示。

enter image description here

展开/折叠工作正常,但我不知道如何处理子视图。

在我的自定义视图的构造函数中,我膨胀了一个 xml 布局,里面有一个线性布局,我想在其中放置子元素。

我尝试使用 question here.

的答案中建议的解决方案

但我收到 StackOverflowError,以及大约数百个这样的错误: “at android.view.ViewGroup.resetResolvedLayoutDirection(ViewGroup.java:7207)”,即使我尝试在第二个aswer中使用解决方案,使用while循环而不是for。

这是我的 kotlin 类:

    class CollapsableCategoryView(context: Context,attrs: AttributeSet) : LinearLayout(context,attrs) {

      /** Declare some variables */
      private var titleString : String = ""
      private var subtitleString : String = ""
      private var isExpaneded : Boolean = false

      /** The required views */
      private lateinit var ivIcon : ImageView
      private lateinit var llExpandableContent : LinearLayout

      init {

        /** Receive the attributes */
        context.theme.obtainStyledAttributes(
            attrs,R.styleable.CollapsableCategoryView,0
        ).apply {
            try {
                titleString = getString(R.styleable.CollapsableCategoryView_categoryTitle) ?: ""
                subtitleString = getString(R.styleable.CollapsableCategoryView_categorySubtitle) ?: ""

            } finally {
                recycle()
            }
        }

        /** Inflate the layout */
        val root : View = View.inflate(context,R.layout.collapsable_task_category,this)

        /** Find the views we need*/
        ivIcon = root.findViewById(R.id.ivCollapsableCategoryIcon) as ImageView
        llExpandableContent = root.findViewById(R.id.llExpandableContent) as LinearLayout

        /** onClickListener for the icon */
        ivIcon.setOnClickListener {
            toggleExpanded()
        }
      }

      override fun onFinishInflate() {

        for(i in 0..childCount){
            var view : View = getChildAt(i)
            removeViewAt(i)
            llExpandableContent.addView(view)
        }

        super.onFinishInflate()

      }

      /** This method is called when user clicks the expand/collapse button */
      fun toggleExpanded(){
        isExpaneded = !isExpaneded
        if(isExpaneded)
        {
            ivIcon.setImageResource(R.drawable.ic_collapse)
            llExpandableContent.visibility = VISIBLE
        }else{
            ivIcon.setImageResource(R.drawable.ic_expand)
            llExpandableContent.visibility = GONE
        }
      }
    }

我在其他地方读到了一个不同的解决方案,但它也不起作用。该解决方案建议像这样覆盖 addView() 方法:

override fun addView(child: View?,index: Int,params: ViewGroup.LayoutParams?) {
        llExpandableContent.addView(child,params)
    }

但如果我这样做,我会得到一个异常,即 lateinint var llExpandableContent 从未被初始化。

我也看到了覆盖 onMeasure() 方法的解决方案,但这对我来说似乎不是解决这个问题的正确方法,因为我不想以特殊的方式表达我的观点,只是想以线性布局添加它们。

这里是自定义视图布局的xml资源文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/collapsable_category_corner_radius"
        android:background="@drawable/bg_collapsable_category_top"/>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/clCollapsableCategoryMain"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/bg_collapsable_category_middle">

        <ImageView
            android:id="@+id/ivCollapsableCategoryIcon"
            android:layout_width="38dp"
            android:layout_height="38dp"
            android:layout_marginStart="8dp"
            android:src="@drawable/ic_expand"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/clCollapsableCategoryTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="Title"
            app:layout_constraintStart_toEndOf="@+id/ivCollapsableCategoryIcon"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/clCollapsableCategorySubtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Subtitle"
            app:layout_constraintStart_toEndOf="@+id/ivCollapsableCategoryIcon"
            app:layout_constraintTop_toBottomOf="@+id/clCollapsableCategoryTitle" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <LinearLayout
        android:id="@+id/llExpandableContent"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/bg_collapsable_category_middle"
        android:visibility="gone">
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="@dimen/collapsable_category_corner_radius"
        android:background="@drawable/bg_collapsable_category_bottom"/>

</LinearLayout>

这是我尝试在布局 xml 文件中使用自定义视图的方式:

<com.test.test.util.CollapsableCategoryView
   android:layout_width="match_parent"
   android:layout_height="wrap_content">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Child view 1"/>

</com.test.test.util.CollapsableCategoryView>

有谁知道如何解决这个问题? 非常感谢您提供任何帮助。最好的祝福, 阿戈斯顿

解决方法

所以我在另一个问题上找到了解决方案,我再也找不到了... 但是这个解决方案就像一个魅力:)

override fun addView(child: View?,index: Int,params: ViewGroup.LayoutParams?) {
    if(llExpandableContent == null){
        super.addView(child,index,params)
    }else{
        llExpandableContent?.addView(child,params)
    }
}

希望它会在某个时候帮助其他人:)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...