android - 如何从 xml 文件重新创建创建的视图?
问题描述
想象一下,我在 xml 文件中定义了一个 ImageButton,
我设置它并在移动屏幕上看到 ImageButton
现在,我想删除它,然后在同一个地方重新创建它,但这次使用新设置
当我在代码中创建 ImageButton 时,我可以简单地执行此类操作
只需我可以删除视图并添加新视图
我的问题是xml文件中的ImageButton
当我删除它然后它被删除但我不能在那里重新创建它
解决方案
您在这里有两个选择:
1)不要在布局文件中嵌入按钮。即时生成按钮并将其添加到您的视图中。
例子:
fun createButton(context:Context):Button{
val btn = Button(context)
btn.text = "Magic"
btn.setOnClickListener { Toast.makeText(context, "You clicked me!", Toast.LENGTH_SHORT).show() }
return btn
}
要添加按钮的位置:
val parent = findViewById<LinearLayout>(R.id.parent)
btnAdd.setOnClickListener{
val btn = createButton(this)
parent.addView(btn)
}
btnRemove.setOnClickListener{
parent.removeViewAt(0)
}
2)第二种方法,如果你想有一个布局文件,是用这样的按钮创建一个自定义布局:
button_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Magic" />
</LinearLayout>
在您的活动中,有一个父布局(您选择的任何布局):
<LinearLayout
android:id="@+id/parent"
android:layout_width="409dp"
android:layout_height="354dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.254"/>
我在这个例子中使用了线性布局。
现在在活动中,扩展自定义布局并将其添加到您的视图中:
val parent = findViewById<LinearLayout>(R.id.parent)
btnAdd.setOnClickListener{
val btnView = LayoutInflater.from(this).inflate(R.layout.button_layout, null)
btnView.findViewById<Button>(R.id.btnTest).text = "Some other text"
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
parent.addView(btnView, lp)
}
btnRemove.setOnClickListener{
parent.removeViewAt(0)
}
在上面的示例中,我有两个按钮,添加和删除,分别添加自定义布局和删除它。
这样做的好处是,在充气之后,根据条件,你可以这样做:
btnView.findViewById<Button>(R.id.btnTest).text = "Some other text"
并仅更改您需要更改的部分(例如文本/图像)并保持其余样式相同。
这适用于任何按钮(普通或图像按钮)。
希望这个例子有帮助,如果您有任何其他疑问,请告诉。
问候
普里亚布拉塔
推荐阅读
- ruby - XPath 中的 `@attr!="value"` 和 `not(@attr="value")` 有什么区别
- python - 从 sklearn 数据集中随机采样数据
- javascript - 想知道为什么没有按预期工作?
- sql - SQL 根据其他列返回列
- c# - 从发件人处查找打开的表单
- mysql - GROUP BY 一列和 COUNT 两列
- apache-spark - 拆分数据框中的文本并检查是否包含子字符串
- jdbc - 有没有办法在 EMR 中加载 install-interpreter.sh 文件以加载第 3 方解释器?
- android - 我的对话框片段中的复选框,选中后不会再次显示对话框
- javascript - 无法解析时间字符串