Android中ListView数据不显示问题

一、简介:

最近使用listView来显示蓝牙设备列表,运行后发现什么都没有显示。

二、调试:

1、在自定义Adapter重写的getView方法中添加一条日志,发现运行后该日志并没有打印出来,说明getView方法并没有执行

2、检查传入自定义Adapter的数据列表ArrayList,在ArrayList添加数据后添加日志打印,发现运行后日志能打印出数据,说明ArrayList中是有数据的

三、问题:

为什么传入自定义Adapter中的ArrayList是有数据,但是却显示不出来?

四、分析:

重新看了一遍代码中相关的listView以及Adapter部分

ArrayList数据部分:

List<BluetoothDevice> mPairedDevList = new ArrayList<BluetoothDevice>();
List<BluetoothDevice> mNewDevList = new ArrayList<BluetoothDevice>();

自定义Adapter部分:

MyPairedDeviceAdapter mPairedBlueDeviceAdapter = new BlueDeviceAdapter(this,R.layout.device_name_item,mPairedDevList);
MyNewDeviceAdapter    mNewBlueDeviceAdapter = new BlueDeviceAdapter(this,R.layout.device_name_item,mNewDevList);

ListView绑定Adapter部分:

ListView mPairedDeviceListView = findViewById(R.id.paired_device_list_view);
ListView mNewDeviceListView = findViewById(R.id.new_device_list_view);
mPairedDeviceListView.setAdapter(mPairedBlueDeviceAdapter);
mNewDeviceListView.setAdapter(mNewBlueDeviceAdapter);

1、发现我三部分的代码都是写在onCreate中,添加数据到ArrayList的部分代码写在后面,也就是说,我后面添加到ArrayList中的数据都没有加载到ListView中,导致后面放进ArrayList中的数据没有显示。

2、我创建ArrayList后并没有添加任何数据就绑定ListVIew,导致ArrayList中的数据为空,这种情况当然不能显示出来。

五、解决方案:

(一)对于不需要改变ArrayList中的内容的,即ListView布局中的内容是固定不变的情况

  • 先将所需要显示的数据添加到空的ArrayList中

  • 然后将带有数据的ArrayList对象作为参数传入自定义MyAdapter的第三个参数中

  • 最后将ListView绑定MyAdapter

例子:

//创建mArrayList对象
ArrayList<device> myArrayList = new ArrayList<device>();

//添加所需显示的数据到mArrayList中
myArrayList.add(device1);
myArrayList.add(device2);

//将mArrayList传入到MyAdapter的MyAdapter对象
MyAdapter myAdapter = new MyAdapter(this,R.layout.xxx,myArrayList);

//将ListView绑定MyAdapter
mListView.setAdapter(myAdapter);

注意:这种情况ArrayList必须先传入数据,否则ArrayList为空,这样的话ListView布局中就没有数据了

(二)对于ArrayList内容会变化,即ListView布局中的内容会改变的情况

  • 在ArrayLIst每次添加数据后,调用自定义Adapter的notifyDataSetChanged()方法

官方文档中的解释如下:

Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

意思大致是:

每次该方法调用的时候会检查Adapter中传入的数据是否有改变,并且对改动数据相关的View进行相应的更新

因此每次自定义MyAdapter中的数据ArrayList改变的时候,调用该方法即可刷新改动数据对应的布局,显示更新后的布局

例子:

//创建mArrayList对象
ArrayList<device> myArrayList = new ArrayList<device>();

//将mArrayList传入到MyAdapter的MyAdapter对象
MyAdapter myAdapter = new MyAdapter(this,R.layout.xxx,myArrayList);

//将ListView绑定MyAdapter
mListView.setAdapter(myAdapter);

//添加数据
myArrayList.add(device1);
myArrayList.add(device2);

//刷新
MyAdapter.notifyDataSetChanged();

注意:notifyDataSetChanged()方法在检查到数据变动后会调用getView重新加载一遍显示的数据,达到更新ListView布局的效果

六、总结:

对于ListView数据显示问题,个人认为getView方法是否调用以及传入的数据是否为空是显示问题的关键,可以先检查在ListView绑定Adapter前,自己传入Adapter中的数据是否为空,如果为空的话,连数据都没有,当然是不会调用getView的,因此也显示不出来。

如有错误,欢迎指正,虚心学习!

猜你喜欢

转载自blog.csdn.net/Xiongjiayo/article/details/81703678