java - MultiLine Listview 随机排序
问题描述
所以我在 Android Studio 中有两行 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
<?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"
/>
并且由于某种原因,这些项目没有按我想要的方式显示。它们以随机顺序显示,而不是按照它们在代码中格式化的顺序。 应用预览
我怎样才能解决这个问题?
解决方案
迭代 aHashMap
不能保证以与添加元素相同的顺序访问元素。如果需要该属性,请使用 aLinkedHashMap
或 an ArrayList
。前者将更容易让您将现有代码转换为,只需替换
HashMap<String, String> nameAddresses = new HashMap<>();
和
LinkedHashMap<String, String> nameAddresses = new LinkedHashMap<>();
推荐阅读
- r - 附加具有不同列数量和拼写的 csv
- python - 代码无法与树莓派一起使用时遇到问题
- reactjs - 反应如何在按下另一个位置时隐藏卡片
- php - 如何制作排行榜
- android - 如何在 Firebase 实时数据库中上传带有附加数据的图像?
- coq - 坚持使用列表归纳的 Coq 证明
- python-3.x - Python - 基于不同的列转置/旋转列
- sql-server - 多个索引或覆盖索引和包含?
- flutter - Flutter 中 ListView.builder 上的 GestureDetector
- jolt - 将一个数组移动到另一个数组中定义的 json 对象中 - JOLT 转换