问题描述
我正在尝试以编程方式创建按钮并将其添加到线性布局中。我正在从 API 中检索琐事问题,这些问题具有动态数量的可能答案。
我将答案列表传递给一个函数,然后尝试为每个答案创建一个按钮:
for (answer in answers) {
// runs okay if you do not cast as button
val answerButton = View.inflate(requireContext(),R.layout.answer_button,binding.answersLinearLayout) as Button
answerButton.text = answer // but need to cast as button to set text
}
这使用了一个仅包含我的 XML 按钮的布局。然后我想为尽可能多的答案膨胀这个,我必须为其创建一个按钮。
然而,奇怪的是当我不将这个膨胀的视图转换为一个按钮时,它会正常运行并循环我有多少答案。但是当我将它投射到一个按钮时,该按钮只膨胀一次并且不再运行(使用断点确认)。
我需要将它正确地转换为按钮而不是通用视图,因为我需要在按钮上设置文本。
为什么将其转换为 Button 会突然中断我的循环?是否退出/打破/返回循环?
编辑:这是我的 R.layout.answer_button 布局
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
解决方法
您的演员表不成功,这导致了错误。 但是,您可以像这样以编程方式完成整个过程。
for (answer in answers) {
LinearLayout linearLayout = new LinearLayout(this);
Button button = new Button(this);
button.setText(answer);
button.setTextSize(20);
button.setGravity(Gravity.CENTER);
linearLayout.addView(button);
this.setContentView(linearLayout,new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
}