最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Android中的ListView如何清除所有子View

Android crifan 7564浏览 0评论

【背景】

Android中ListView,想要将之前add进入的chind view清除掉。

【解决过程】

1.自己先去找了下,是否有clearAll的函数,然后发现,默认的是有类似的功能,但是有些没实现:

removeAllViews()

 

listview removeAllViews not implemented

而有些又暂时不太建议用:

public void removeAllViewsInLayout ()

Added in API level 1

Called by a ViewGroup subclass to remove child views from itself, when it must first know its size on screen before it can calculate how many child views it will render. An example is a Gallery or a ListView, which may "have" 50 children, but actually only render the number of children that can currently fit inside the object on screen. Do not call this method unless you are extending ViewGroup and understand the view measuring and layout pipeline.

Note: do not invoke this method from draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

所以,还是去网上找找吧。

2.搜:

android listview remove all child

参考:

android – How to remove listview all items – Stack Overflow

写代码:

 private void clearAdapterList(){
  deviceAdapters.clear();
 
  AdapterListAdapter listAdapter = new AdapterListAdapter(this, deviceAdapters);
  final ListView listView = (ListView) findViewById(R.id.adapterList);
  if (listView != null) {
   listView.setAdapter(listAdapter);
  }
 }

应该就可以了。

3.参考:

Remove ListView items in Android – Stack Overflow

去试试clear:

try listview clear work or not

很明显,是没有clear这个功能的:

和我之前自己研究的结果一样,是没有clear的。

不过才注意到:

其是让adapterList去clear,不是ListView去clear的。。。

而这个,是我本来就已经实现了的。。。

4.另外一个地方,也是类似的写法:

 private void clearPreviousDeviceList(){
  DeviceListAdapter emptyAdapter = new DeviceListAdapter(this, new ArrayList<DeviceItem>());
  ListView listView = (ListView) findViewById(R.id.deviceList);
  listView.setAdapter(emptyAdapter);
 }

就可以实现,清楚之前的列表的内容了。

【总结】

想要清楚ListView的话,则可以去:

生成一个空的Adapter的list,然后再ListView的setAdapter传入该空表,即可。

用类似如下的写法:

  SomeAdapterList emptyList = new SomeAdapterList();
  ListView listView = (ListView) findViewById(R.id.some_list);
  listView.setAdapter(emptyList);

即可。

转载请注明:在路上 » 【已解决】Android中的ListView如何清除所有子View

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.287 seconds, using 22.12MB memory