遍历ArrayList以便在第二个Activity Java中显示在多行ListView中?

时间:2018-09-24 02:51:10

标签: java android listview arraylist

我创建了第二个活动,以显示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

预先感谢,不确定该问题是否完全有意义。

2 个答案:

答案 0 :(得分:1)

您将要使用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附加功能:

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);

答案 1 :(得分:0)

  

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