java - 在第二个 Activity Java 中循环遍历 ArrayList 以在多行 ListView 中显示?
问题描述
我创建了第二个 Activity 来显示 ArrayList 中的所有元素。例如,如果 ArrayList 在 MainActivity 中包含以下内容:
//This is an Object type
thingsList = ["This is list1","This is list2"];
Intent intent = new Intent(this, Activity2.class);
Bundle b = new Bundle;
b.putString("Lists", thingsList.toString());
intent.putExtras(b);
startActivity(intent);
我的 Activity2.java 中有这个
ListView newListView = (ListView)findViewById(R.id.newListView);
Bundle b = getIntent().getExtras();
String newList = b.getString("Lists");
ArrayAdapter adapterList = new ArrayAdapter(this, R.layout.list_label, Collections.singletonList(newList));
newListView.setAdapter(adapterList);
它现在所做的是:
[This is list1, This is list2]
如何循环遍历arraylist并使其显示在不同的行上
This is list1
This is list2
我试过这样做但没有奏效
thingsList = ["This is list 1","This is list 2"];
Intent intent = new Intent(this, Activity2.class);
Bundle b = new Bundle;
for (Object makeList: thingsList) {
b.putString("Lists", makeList.toString());
intent.putExtras(b);
}
startActivity(intent);
它所做的只是抓取数组列表中的最后一个元素,例如
This is list2
在此先感谢,不确定这个问题是否有意义。
解决方案
是的,适当的方法是@Ben P 建议的。
我只是指出您尝试过的方法中的错误。
thingsList = ["This is list 1","This is list 2"];
Intent intent = new Intent(this, Activity2.class);
Bundle b = new Bundle;
for (Object makeList: thingsList) {
b.putString("Lists", makeList.toString());
intent.putExtras(b);
}
startActivity(intent);
由于 Bundle 对象是在 for 循环之外创建的,因此最后一个值将被前一个值覆盖。
您应该每次都制作新对象,如下所示
for (Object makeList: thingsList) {
Bundle b=new Bundle();
b.putString("Lists", makeList.toString());
intent.putExtras(b);
}
推荐阅读
- reactjs - 我没有读到属性绑定
- python-3.x - `python -m venv foo` 不在嵌套环境中安装 pip
- r - ggplot2 PDF barplot 有白线,需要大量放大并且看起来不同。在 PowerPoint 上
- ruby - 在 Ruby 中,如何不带括号将多个哈希传递给一个方法?
- numpy - Numpy:通过相对舍入克服机器不精确
- python - 如何将逆向转置应用于 numpy 数组
- swift - 如何从 GRDB 中的只读数据库连接中调用新的数据库连接?
- topojson - 有没有办法改变 topojson 文件中的投影?
- angular - 如何以角度进行多个异步并行获取调用而不等待响应
- ios - 使用 CoreData @NSManaged 子类在不寻常的地方“将无法识别的选择器发送到实例”