kotlin - 重新打开使用 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) 重新创建它时,它会重新创建但它不会在屏幕上显示!
我在调试器中看到程序已创建但屏幕上什么也没有出现?
任何帮助将不胜感激。安卓
解决方案
问题是您正在检查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
...
}
}
推荐阅读
- angular - 如何使用 Stencil.js 更新插槽中传递的元素?
- flask - 运行Flask时终端中的“←[37m”是什么意思?
- javascript - 某些键值对不会显示在 mongoDB 的数据库中。为什么可能是原因?
- c - 执行我的 OpenGL C 程序以实现 Bresenham 的画线算法时出错。中止(核心转储)
- sql - 如果A列中的值为null,那么如何返回B列的值,如果B也是null,那么如何移动到C的值
- javascript - 从服务器发送的 javascript 对象在客户端没有方法
- reference - 在 Tableau 中将日期与 makedate 匹配
- android - 如何更新房间数据库中的检查 recyclerview 列表?
- database - 关机后如何启动 pg_cron 扩展
- c - 使用密码的公钥加密:允许使用公共盐吗?