首页 > 解决方案 > 重新打开使用 kotlin 以编程方式创建并由 Gone 关闭的 ScrollView

问题描述

我以编程方式创建了一个滚动视图

从 .xml 文件中提取

<!-- Spinner -->
<RelativeLayout
    android:id="@+id/myScrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="100dp"
    android:layout_marginRight="100dp"
    app:layout_constraintTop_toBottomOf="parent"
    android:layout_marginTop="125dp"
    tools:context=".QuizActivity">

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="horizontal">

    <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="left"
        android:background="@color/white"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="15dp"/>
</HorizontalScrollView>
</RelativeLayout>

这里 .kt 代码片段

/***************** SCROllL VIEW *****************/
fun showSpinner(show: Boolean) {
    if (linearLayout == null) {
        linearLayout = findViewById(R.id.linear1)
        if (show) {
            val layoutInflater = LayoutInflater.from(this)
            ...
            ...
        } else {
            // Close de scrollView
            // TODO: fermer le spinner
            if (linearLayout!! != null) {
                linearLayout!!.visibility = View.GONE

            }

            // TODO: Add a frame auround the scroll view to get a better look
        }
    }
}   

但是现在当我需要再次使用 showSpinner(true) 重新创建它时,它会重新创建但它不会在屏幕上显示!

我在调试器中看到程序已创建但屏幕上什么也没有出现?

任何帮助将不胜感激。安卓

标签: kotlinlayoutscrollview

解决方案


问题是您正在检查linearLayout函数开头是否为空。
由于您在第一个块内设置它的值,因此在第一个方法调用if 后不会执行代码。showSpinner

更好的做法是在 ActivityonCreate方法或 FragmentonCreateView方法中初始化布局(取决于您声明此代码的位置)

尝试像这样更改您的代码(我假设您在活动中)

private var linearLayout: LinearLayout? = null

override fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(<your-layout-ID>)

    linearLayout = findViewById(R.id.linear1)
}

fun showSpinner(show: Boolean) {
    if (show) {
        val layoutInflater = LayoutInflater.from(this)
        ...

        linearLayout?.visibility = View.VISIBLE
    } else {
        linearLayout?.visibility = View.GONE
        ...
    }
}   

推荐阅读