从ListView中删除头ListView

2023-09-04 12:36:12 作者:倾听悲伤小旋律

我想从的ListView 删除页眉时有一些问题。起初,我用 addHeaderView()添加它,但是当我切换到另一个布局,我希望它消失,但 removeHeaderView()不工作...

I'm having some problems when trying to remove the header from a listView. At first I use addHeaderView() to add it, but when I change to another layout I want it to disappear but removeHeaderView() doesn't work...

我也试着设置能见度消失了,它不会消失......

I also tried setting visibility to GONE and it doesn't disappear...

我该怎么办?

在此先感谢

推荐答案

试试下述方法。

Android的的ListView#addHeaderView 的ListView#addFooterView 方法是奇怪的:你必须添加页眉和页脚视图然后再设置ListView的适配器,以便在ListView可以把页眉和页脚考虑 - 否则,你得到一个异常。在这里,我们添加一个进度条(微调)作为headerView:

Android ListView#addHeaderView and ListView#addFooterView methods are strange: you have to add the header and footer Views before you set the ListView's adapter so the ListView can take the headers and footers into consideration -- you get an exception otherwise. Here we add a ProgressBar (spinner) as the headerView:

//微调是一个进度条

// spinner is a ProgressBar

listView.addHeaderView(spinner);

我们希望能够显示和隐藏微调的意愿,而是彻底删除它是危险的,因为我们从来没有能够再次添加它不破坏ListView控件 - 记住,我们不能addHeaderView后我们已经是适配器:

We'd like to be able to show and hide that spinner at will, but removing it outright is dangerous because we'd never be able to add it again without destroying the ListView -- remember, we can't addHeaderView after we've it's adapter:

listView.removeHeaderView(spinner); //dangerous!

所以,让我们把它隐藏!原来,这是很难得。只是隐藏微调视图本身导致空,但仍清晰可见,头区域。

So let's hide it! Turns out that's hard, too. Just hiding the spinner view itself results in an empty, but still visible, header area.

现在试图隐藏微调:

spinner.setVisibility(View.GONE);

结果:头区有一个丑陋的空间仍清晰可见:

Result: header area still visible with an ugly space:

解决的办法是把进度条中的LinearLayout一个包装它的内容,和隐藏的内容。这种方式缠绕的LinearLayout会倒塌时其含量是隐藏的,从而导致一个headerView在技术上仍然present,但0dip高:

The solution is to put the progress bar in a LinearLayout that wraps it's content, and hiding the content. That way the wrapping LinearLayout will collapse when its content is hidden, resulting in a headerView that is technically still present, but 0dip high:

<LinearLayout 
      xmlns:a="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
    <!-- simplified -->
      <ProgressBar
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/> 
  </LinearLayout>

然后,设置布局标题:

Then, set the layout as the header:

spinnerLayout = getLayoutInflater().inflate(R.layout.header_view_spinner, null);
listView.addHeaderView(spinnerLayout);

当我们需要将其隐藏,隐藏布局的内容,而不是布局:

And when we need to hide it, hide the layout's content, not the layout:

spinnerLayout.findViewById(R.id.spinner).setVisibility(View.GONE);

现在的头从视野中消失。在顶部没有更多的丑陋的空间!

Now the header disappears from view. No more ugly space at the top!