【问题标题】:View won't update in dialog after creation创建后视图不会在对话框中更新
【发布时间】:2021-03-26 15:51:59
【问题描述】:

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

我有一个 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 (不知道为什么不起作用),现在正在调用监听器,我什至放了一个断点并调试了它及其设置可见性,但它没有任何效果,也不会导致任何错误,所以我似乎无法在这里找到问题

【问题讨论】:

  • 任何带有绑定的动作都不会在监听器内部起作用,即使我指定了另一个要调用的函数,它也不能用于绑定,但绑定不是问题!它工作正常

标签: android android-viewbinding


【解决方案1】:

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

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

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

 val myvar = binding.monthLayout

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2011-01-19
    相关资源
    最近更新 更多