Android开发:创建ListView出现显示异常的问题求助
解决ListView显示错误固定信息的问题
嘿,我看了你的代码,马上就发现了两个导致ListView显示异常的关键问题,咱们一步步来解决:
问题1:SimpleAdapter用错了布局文件
你在创建SimpleAdapter的时候,第三个参数传的是R.layout.activity_main——这可是整个主界面的布局啊!这就导致ListView的每个item都会加载一遍顶部的固定信息(图片、搜索栏这些),自然看不到你想要的文件名列表了。
你需要为ListView的item单独创建一个简单的布局文件,比如res/layout/list_item.xml,里面只放用来显示文件名的TextView:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/topic_id" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:textSize="16sp"/>
问题2:数据键不匹配
你往HashMap里存数据用的键是"file_name",但SimpleAdapter的from数组里写的却是{"name"}——两者完全不对应,Adapter根本找不到要显示的数据,这也是内容无法正确展示的原因之一。
修改MainActivity里的Adapter代码
把这两处错误修正过来,代码改成这样:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); copyFromAssets();//将信息存储到filePaths ListView lv = findViewById(R.id.list_view); ArrayList<HashMap<String,String>> arrayList=new ArrayList<>(); for (int i=0;i<filePaths.size() ;i++) { HashMap<String,String> hashMap=new HashMap<>();//创建哈希映射以键值对形式存储数据 hashMap.put("file_name",filePaths.get(i)); arrayList.add(hashMap);//将哈希映射添加到数组列表 } // 修正键名,和HashMap里的一致 String[] from={"file_name"}; int[] to={R.id.topic_id}; // 第三个参数改为我们刚创建的item布局 SimpleAdapter simpleAdapter=new SimpleAdapter(this,arrayList,R.layout.list_item,from,to); lv.setAdapter(simpleAdapter); }
另外提个小细节:你的FrameLayout设置了android:layout_height="match_parent",虽然RelativeLayout的layout_below已经让它在搜索栏下方,但如果想让它刚好适配ListView的高度,也可以改成wrap_content,不过这个不影响核心功能,看你需求调整就行。
这样修改之后,ListView就能正确显示filePaths里的字符串,不会再重复显示顶部的固定信息啦!
内容的提问来源于stack exchange,提问作者Keselme
相关产品推荐
相关产品推荐

