【问题标题】:Custom View - CheckBoxes not preserving state on rotation [duplicate]自定义视图 - 复选框不保留旋转状态[重复]
【发布时间】:2021-02-15 11:51:11
【问题描述】:

我对包含 CheckBox 的 CustomView 有一个奇怪的问题。当我在布局中使用其中的多个时,复选框无法正确保存状态。要么选中所有 CheckBox,要么在轮换后全部取消选中。

这是自定义视图的示例:

class CustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {

    private val binding = ViewCustomBinding.inflate(LayoutInflater.from(context), this)

    init {
        orientation = HORIZONTAL
    }
}

这是布局文件:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="wrap_content"
    tools:parentTag="android.widget.LinearLayout">

    <CheckBox
        android:id="@+id/check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:text="A Check box" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_margin="12dp" />

</merge>

然后在我的片段文件中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.watchqueue.ui.view.CustomView
        android:id="@+id/custom_view_0"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <com.watchqueue.ui.view.CustomView
        android:id="@+id/custom_view_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

如何解决?

【问题讨论】:

    标签: android


    【解决方案1】:

    当屏幕方向改变时,Android 会销毁所有现有视图并重新创建它们,因此所有未保存的 UI 更改也会重置。如果可能,您需要保存视图状态并在屏幕方向更改时再次恢复,或者禁用此视图的方向更改。 这是一篇关于改变方向的好文章:https://medium.com/hootsuite-engineering/handling-orientation-changes-on-android-41a6b62cb43f

    【讨论】:

    • 大多数 Android 视图会保存自己的状态,复选框也会这样做。
    • 问题解决了吗?我试图在一个新的简单项目中重现您的案例,也使用 CustomView 和 ViewBinding 并且不能,一切正常(在 API24、27 上检查)@TomislavTurcic
    • 是的,我在这里找到了答案:stackoverflow.com/questions/60623460/…
    • 转载,只是添加了几个复选框。以前从未遇到过,谢谢,很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2013-06-14
    • 2017-01-04
    • 2016-10-13
    • 2020-06-11
    相关资源
    最近更新 更多