android - 通过for循环创建TextView,只有第一个创建的工作
问题描述
我正在尝试创建一个 TextView 的早午餐并通过 for 循环在屏幕上显示它们。
但只有第一个 TextView 显示分配的值“123”。
仍然创建了许多 TextView 但只有第一个显示值。
我想我错过了什么,但你知道我错过了什么吗?
谢谢。
创建():
LinearLayout busStopLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
// skipped
busStopLinearLayout = (LinearLayout) findViewById(R.id.bus_stop_linear_layout);
// skipped
}
我要求的 for 循环:
for (int i = 0; i < closestStop.size(); i++) {
TextView dummyTxt = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
dummyTxt.setLayoutParams(params);
dummyTxt.setText("123");
busStopLinearLayout.addView(dummyTxt);
busStopTextArray.add(dummyTxt);
}
活动.xml
<LinearLayout
android:id="@+id/bus_stop_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
解决方案
试试这个
LinearLayout busStopLinearLayout = (LinearLayout) findViewById(R.id.busStopLinearLayout);
for(int i=0; i<closestStop.size(); i++){
TextView text = new TextView(this);
text.setText("123");
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
busStopLinearLayout.addView(text);
}
推荐阅读
- python - check_hostname 需要币安的 server_hostname
- java - Spring Boot Batch:获取 Reader 可连接的 ExecutionContext
- java - 如何在 JFrame 中将图像设置为背景
- mysql - 为什么我的默认值在 MySQL 中不起作用
- css - 使用旧 CSS 样式表的浏览器?
- r - dplyr 根据某些条件创建新列
- c++ - 定向光的全向阴影
- python - 使用 Django 的重新组合模板标签重新组合列表项后如何对列表项进行打乱/随机化
- python - 带有 URL 的 Python YouTube 视频下载器
- java - 为什么使用完整路径从文件系统读取文件时出现错误?