首页 > 解决方案 > 创建后视图不会在对话框中更新

问题描述

当然是一个简单的问题,但我已经尝试了几个小时,但我似乎无法解决问题!

我有一个DialogFragment包含一个

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/interval_input_layout"
        style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:boxStrokeWidth="0dp">

        <AutoCompleteTextView
            android:id="@+id/time_interval_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none"
            tools:ignore="LabelFor" />

    </com.google.android.material.textfield.TextInputLayout>

这是在此 AutoCompleteView 上设置的侦听器

binding.untilInput.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                when (position) {
                    0 -> {
                        binding.numberLayout.visibility = View.GONE
                    }
                    1 -> {
                        binding.numberLayout.visibility = View.GONE
                    }
                    2 -> {
                        binding.numberLayout.visibility = View.VISIBLE
                    }
                }
            }

虽然数字布局只是这样的线性布局

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/number_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="16dp">

        <com.google.android.material.textview.MaterialTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="For number of events"
            android:textColor="?android:textColorSecondary" />

    </androidx.appcompat.widget.LinearLayoutCompat>

起初没有调用监听器所以我这样设置它而不是直接调用函数 setOnItemClickListener (不知道为什么这不起作用),现在正在调用监听器,我什至放了一个断点并调试它及其设置可见性,但没有任何效果,也不会导致任何错误,所以我似乎无法在这里找到问题

标签: androidandroid-viewbinding

解决方案


使用DialogFragment我在OnCreateView方法中使用数据绑定来扩展视图布局,然后在OnViewCreated中我使用我的视图并导致 UI 发生更改并为其设置侦听器并再次导致
OnCreateDialog中更改 UI我调用了这两个方法onCreateView(获取视图并将其设置为对话框)和onViewCreated设置视图

我尝试使用findViewById查找视图只是为了确保数据绑定是否工作正常并且工作正常但可见性仍然不会改变并且视图不会更新!
我仍然没有找到问题的根源,但似乎你必须将视图存储在一个变量中,这样你就不会在调用onClickListener时丢失对它的引用,在我看来,就在调用 onClickListener 时绑定的视图变得无效,它应该但小问题是我没有调用onDestroy使绑定为空,因为当时绑定无效!

现在我只是像这样存储对绑定的引用

 val myvar = binding.monthLayout

我在 onClickListener 中捕获 myvar 的值,不是使用绑定


推荐阅读