简体   繁体   English

MultiLine Listview随机排序

[英]MultiLine Listview sorted randomly

So I have this code for a ListView with 2 lines in Android Studio. 所以我有这段代码用于Android Studio中带有2行的ListView。

 ListView resultsListView = (ListView) findViewById(R.id.AboutListView);

    HashMap<String, String> nameAddresses = new HashMap<>();
    nameAddresses.put("Diana", "3214 Broadway Avenue");
    nameAddresses.put("Tyga", "343 Rack City Drive");
    nameAddresses.put("Rich Homie Quan", "111 Everything Gold Way");
    nameAddresses.put("Donna", "789 Escort St");
    nameAddresses.put("Bartholomew", "332 Dunkin St");
    nameAddresses.put("Eden", "421 Angelic Blvd");

    List<HashMap<String, String>> listItems = new ArrayList<>();
    SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
            new String[]{"First Line", "Second Line"},
            new int[]{R.id.line1, R.id.line2});


    Iterator it = nameAddresses.entrySet().iterator();
    while (it.hasNext())
    {
        HashMap<String, String> resultsMap = new HashMap<>();
        Map.Entry pair = (Map.Entry)it.next();
        resultsMap.put("First Line", pair.getKey().toString());
        resultsMap.put("Second Line", pair.getValue().toString());
        listItems.add(resultsMap);
    }

    resultsListView.setAdapter(adapter);

list_item.xml list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/line1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/colorAccent"
    android:textSize="21sp"
    android:textStyle="bold"
    />

<TextView android:id="@+id/line2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@android:color/holo_green_dark"
android:textStyle="bold"
/>

And for some reason, the items are not showing up how I want. 由于某种原因,这些物品没有显示出我想要的样子。 They're showing in random order not in the order they're formatted in the code. 它们以随机顺序显示,而不是按照在代码中格式化的顺序显示。 app preview 应用预览

How can I fix this? 我怎样才能解决这个问题?

Iterating a HashMap is not guaranteed to access elements in the same order you added them in. If you need that property, use a LinkedHashMap or an ArrayList . 不能保证迭代HashMap可以按添加元素的顺序访问元素。如果需要该属性,请使用LinkedHashMapArrayList The former will be easier for you to convert your existing code to, simply replace 前者将使您更容易将现有代码转换为,只需替换

HashMap<String, String> nameAddresses = new HashMap<>();

with

LinkedHashMap<String, String> nameAddresses = new LinkedHashMap<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM