我创建了第二个 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]
如何循环遍历数组列表并使其显示在不同的行上
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
提前致谢,不确定这个问题是否有意义。
最佳答案
您需要使用 Bundle.putStringArrayList()
而不是 putString()
。而且,在使用 Intent
时,您实际上可以跳过 Bundle
步骤并直接向 Intent 添加额外内容(Android 将在幕后为您创建并填充 Bundle) .
我不知道你是如何获得 thingsList
引用的,但如果它只是一个通用的 List
,最安全的做法是构建一个新的 ArrayList
就在将其添加到包之前。
thingsList = ["This is list1","This is list2"];
// you can skip this if thingsList is already an ArrayList
ArrayList<String> thingsArrayList = new ArrayList<>(thingsList);
Intent intent = new Intent(this, Activity2.class);
intent.putStringArrayListExtra("Lists", thingsArrayList); // or use thingsList directly
startActivity(intent);
然后,在另一方面,您需要将其作为 List
获取。同样,您可以跳过 Bundle
并直接访问 Intent
extras:
ListView newListView = (ListView)findViewById(R.id.newListView);
List<String> newList = getIntent().getStringArrayListExtra("Lists");
ArrayAdapter adapterList = new ArrayAdapter(this, R.layout.list_label, newList);
newListView.setAdapter(adapterList);
关于java - 循环遍历 ArrayList 以在第二个 Activity Java 的多行 ListView 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52472115/