android - 如何使按钮使用现有布局
问题描述
我是 android 新手,并且在很长一段时间内都在为以下问题苦苦挣扎。我在 for 循环中创建了几个按钮。在 res\layout 下,我创建了我想要的按钮外观。是否可以使按钮使用该布局,因为在编辑器中很容易修改它?目前我正在使用 LayoutParams 并通过调用相应的方法来设置所有内容(仅在下面的示例中设置文本“push me”)。
这是我的 MainActivity.java 文件中的代码:
for(int i = 0; i<50; i++) {
Button myButton = new Button (this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
myButton.setLayoutParams(params);
myButton.setText("Push Me");
LinearLayout ll = findViewById(R.id.myLayout);
ll.addView(myButton);
}
这是我希望按钮使用的 buttonlayout.xml 的内容:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/buttonidd">
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
我还想以这种方式创建的每个按钮的 ID 更改为“i”。提前致谢!
解决方案
可以使用 RecyclerView 轻松创建大量类似的组件,对手机来说效果更好。因为 ViewHolder。
如果您需要的组件数量不是很多,并且您想在您的情况下动态调整组件的位置,请注意您的布局使用ConstraintLayout
,所有动态调整的组件都必须设置约束。
推荐阅读
- tensorflow - 在 Keras 模型中使用 Tensorflow 特征列
- java - 项目构建错误:不可解析的父 POM
- imagemagick - 使用 imagemagick 生成文本时出错
- php - PHP strtotime 为结果增加了额外的时间
- transform - 运行 .msi 安装程序后能否确定生成的命令行?
- opengl - 在光栅化过程中顶点是否被丢弃,如果是,如何防止它?
- php - 从时间中删除零
- ionic-framework - 使用时如何刷新列表 (*ngFor) onChange
- sass - 字体命名空间的 stylelint 中断?
- python - 可以修改输出文件以生成数据块吗?