首页 > 解决方案 > 在第二个 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

在此先感谢,不确定这个问题是否有意义。

标签: javaandroidlistviewarraylist

解决方案


是的,适当的方法是@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);
    }

推荐阅读