安卓-无敌解决ListView添加标题头无法正常显示的问题(歪门邪道)

时间:2022-07-22
本文章向大家介绍安卓-无敌解决ListView添加标题头无法正常显示的问题(歪门邪道),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原因:

在做安卓实验时,用到了ListView来做表格显示数据。由于表头是使用xml布局文件动态实现的。造成了添加好组件后,无法正常显示的情况。浪费了我2小时的时间,终于利用歪门邪道解决了。

重点

首先要知道的是使用listView.addHeaderView(view)添加表头时,如果listView中没有数据的话,是不能显示数据的。

  View view  = LayoutInflater.from(this).inflate(R.layout.user_listview_item_header,null);
        listView.addHeaderView(view);

咋整呢

终于

被逼的不行了,就试着继续往下做。我先利用for循环,随便生成了几条数据,发现可以正常显示了,哈哈哈哈。

 List<User> userInfo = new ArrayList<>();
        System.out.println("查出来了:"+userInfo.size());
        for(int i =0;i<10;i++){
            User s = new User();
            s.setId(i);
            s.setUsername("user"+i);
            userInfo.add(s);
        }

        //获取到集合数据
        List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
        for (int i = 0;i<userInfo.size();i++){
            HashMap<String, Object> item = new HashMap<String, Object>();
            User user = userInfo.get(i);
            item.put("item_id", user.getId());
            item.put("item_username", user.getUsername());
            item.put("item_age", user.getAge());
            item.put("item_hight", user.getHeight());
            data.add(item);
        }

        //创建SimpleAdapter适配器将数据绑定到item显示控件上
        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.user_listview_item,
                new String[]{"item_id", "item_username", "item_age","item_hight"}, new int[]{R.id.item_id, R.id.item_username, R.id.item_age,R.id.item_hight});
        //实现列表的显示
        listView.setAdapter(adapter);

机动部

激动不

激动不

激动不

激动不

那就封装一下呗,试试

 //开局查询所有的
    public void selectAll(){
        onSelectClick(new View(this));
    }

初始化完表头,然后执行这个方法

  View view  = LayoutInflater.from(this).inflate(R.layout.user_listview_item_header,null);
        listView.addHeaderView(view);
        selectAll();

这种办法应该不是最好的解决办法,如果哪位大神看到了此篇文章,如果您有更好的解决办法,请给小弟留言。