【问题标题】:Reopen a ScrollView programmatically created with kotlin and closed by Gone重新打开使用 kotlin 以编程方式创建并由 Gone 关闭的 ScrollView
【发布时间】:2021-09-09 12:34:27
【问题描述】:

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

从 .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代码sn-p

/***************** 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) 重新创建它时,它会重新创建但它不会显示在屏幕上!

我在调试器中看到程序已创建,但屏幕上没有任何内容?

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

【问题讨论】:

    标签: kotlin layout scrollview


    【解决方案1】:

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

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

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

    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
            ...
        }
    }   
    

    【讨论】:

    • 其实我在贴到这里之前忘记删除了“if (linearLayout == null)”但是问题是一样的。我现在按照你写的那样做了,它可以按我的意愿工作。谢谢卢卡。
    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多