java - 如何在 Java Android 中分配动态名称?
问题描述
您如何使用仅在运行时知道的名称来初始化一个TextView
或任何其他Android组件的名称?
例如:
LinearLayout linLayout = (LinearLayout) findViewById(R.id.dynamicLayout);
linLayout.setOrientation(LinearLayout.VERTICAL);
for(int i = 1; i < 5; i++){
String dynamic_name = "myTextView"+i;
//Create new textView named dynamically
TextView dynamic_name = new TextView(this);
//style textView here etc
linLayout.addView(dynamic_name);
}
解决方案
如何初始化 textView 或任何其他 Android 组件的名称,其名称仅在运行时知道?
你不能。
TextView this_variable_changes
在编译时定义,而String this_variable_changes
在运行时更改。
那么如何根据只能在运行时知道的数字创建可变数量的 textViews 呢?
一旦你TextView
在运行时获得了 s 的数量,以编程方式创建那么多TextView
s 并将它们添加到布局中。
由于上述原因,您不需要动态名称。您可以做的是将收到的金额映射到相应数量的TextView
s,即Map
与索引到收到的金额和TextView
s 值的键一起使用。
推荐阅读
- google-sheets - 我怎样才能有空列?
- python - 无法使用正则表达式获取某些内容
- typescript - 如何从输入字段更新日期选择器的值,Angular 5 Angular Material 5
- .net - 如何在 VS 2015 中通过 DataGridView 更新数据
- python - 多处理运行意外的代码块
- excel - Excel公式:如何用大写字母分割字符串
- json - 我想将查询存储为 JSON 对象。(错误:SELECT INTO 语句中不允许使用 FOR JSON 子句。)
- reactjs - 反应图像加载
- python - 导入包适用于一个文件,但返回另一个文件错误
- spring-boot - Spring Boot 2.0.0+ 分页、maven 和 hibernate